name: ci-cd
on:
  push:
    branches: [azure-deploy]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-dotnet@v4
        with: { dotnet-version: '8.0.x' }
      - run: dotnet test API/ROLAC.API.Tests/ROLAC.API.Tests.csproj -c Release

  build-push:
    needs: test
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: docker/login-action@v3
        with:
          registry: git.golife.love
          username: ${{ github.actor }}
          password: ${{ secrets.REGISTRY_TOKEN }}
      - uses: docker/build-push-action@v6
        with:
          context: ./API
          push: true
          tags: |
            git.golife.love/chrischen/rolac-api:latest
            git.golife.love/chrischen/rolac-api:${{ github.sha }}
      - uses: docker/build-push-action@v6
        with:
          context: ./APP
          push: true
          tags: |
            git.golife.love/chrischen/rolac-app:latest
            git.golife.love/chrischen/rolac-app:${{ github.sha }}

  deploy:
    needs: build-push
    runs-on: ubuntu-latest
    steps:
      - uses: appleboy/ssh-action@v1
        with:
          host: ${{ secrets.VM_HOST }}
          username: ${{ secrets.VM_USER }}
          key: ${{ secrets.VM_SSH_KEY }}
          script: |
            cd /opt/rolac/deploy
            export TAG=${{ github.sha }}
            docker compose pull
            docker compose up -d
            curl -fsS https://manage.rolac.org/api/health

  # Always runs (success or failure) so the team gets a build result in Rocket.Chat.
  # A failed or skipped upstream job (skipped means an earlier job failed) reports as failed.
  notify:
    needs: [test, build-push, deploy]
    if: always()
    runs-on: ubuntu-latest
    steps:
      - name: Notify Rocket.Chat
        env:
          BUILD_FAILED: ${{ contains(needs.*.result, 'failure') || contains(needs.*.result, 'cancelled') || contains(needs.*.result, 'skipped') }}
          REPO: ${{ github.repository }}
          REF: ${{ github.ref_name }}
          SHA: ${{ github.sha }}
          ACTOR: ${{ github.actor }}
          COMMIT_URL: ${{ github.server_url }}/${{ github.repository }}/commit/${{ github.sha }}
          WEBHOOK: ${{ secrets.ROCKETCHAT_WEBHOOK }}
        run: |
          if [ "$BUILD_FAILED" = "true" ]; then
            STATUS_TEXT="❌ Build failed"
            COLOR="#e74c3c"
          else
            STATUS_TEXT="✅ Build succeeded"
            COLOR="#2ecc71"
          fi
          SHORT_SHA="${SHA:0:7}"
          curl -fsS -X POST -H 'Content-Type: application/json' --data @- "$WEBHOOK" <<JSON
          {
            "attachments": [
              {
                "title": "$REPO — $STATUS_TEXT",
                "title_link": "$COMMIT_URL",
                "color": "$COLOR",
                "text": "Branch *$REF* · commit $SHORT_SHA · by $ACTOR"
              }
            ]
          }
          JSON
