name: CI/CD

on:
  push:
    branches: [main]
  pull_request:
    branches: [main]

concurrency:
  group: asaditools-cicd-${{ github.ref }}
  cancel-in-progress: true

jobs:
  # ── Build & verify ──────────────────────────────────────────────────────────
  build:
    name: "CI — dotnet build"
    runs-on: ubuntu-latest
    container:
      image: mirror.soroushasadi.com/dotnet/sdk:10.0
      options: --add-host=gitea:host-gateway

    steps:
      - name: Checkout
        env:
          TOKEN: ${{ github.token }}
          REF:   ${{ github.ref }}
        run: |
          git init
          git remote add origin "${{ github.server_url }}/${{ github.repository }}.git"
          git config http.extraheader "Authorization: Bearer ${TOKEN}"
          git fetch --depth=1 origin "${REF}"
          git checkout FETCH_HEAD

      - name: Write NuGet config
        run: |
          cat > /tmp/nuget.ci.config << 'EOF'
          <?xml version="1.0" encoding="utf-8"?>
          <configuration>
            <packageSources>
              <clear />
              <add key="nexus"
                   value="https://mirror.soroushasadi.com/repository/nuget-group/index.json"
                   protocolVersion="3" />
            </packageSources>
          </configuration>
          EOF

      - name: Restore
        run: dotnet restore AsadiTools.csproj --configfile /tmp/nuget.ci.config
        env:
          DOTNET_CLI_TELEMETRY_OPTOUT: 1

      - name: Build
        run: dotnet build AsadiTools.csproj --no-restore -c Release

  # ── Deploy ──────────────────────────────────────────────────────────────────
  deploy:
    name: "Deploy — docker compose"
    runs-on: self-hosted
    env:
      PATH: /usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/snap/bin
    needs: [build]
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'
    timeout-minutes: 30

    steps:
      - name: Checkout
        env:
          TOKEN: ${{ github.token }}
          REF:   ${{ github.ref }}
        run: |
          git init
          git remote add origin "${{ github.server_url }}/${{ github.repository }}.git"
          git config http.extraheader "Authorization: Bearer ${TOKEN}"
          git fetch --depth=1 origin "${REF}"
          git checkout FETCH_HEAD

      - name: Write .env
        run: printf '%s' "$ENV_FILE" > .env
        env:
          ENV_FILE: ${{ secrets.ENV_FILE }}

      - name: Build image
        run: docker compose build asadi-tools
        env:
          DOCKER_BUILDKIT: 1
          COMPOSE_DOCKER_CLI_BUILD: 1

      - name: Start service
        run: docker compose up -d --no-deps asadi-tools

      - name: Wait for healthy
        run: |
          for i in $(seq 1 24); do
            STATUS=$(docker inspect --format='{{.State.Health.Status}}' asadi-tools 2>/dev/null || echo "missing")
            echo "  [$i/24] $STATUS"
            [ "$STATUS" = "healthy" ] && echo "✅ asadi-tools healthy" && break
            [ "$i" = "24" ] && echo "❌ TIMEOUT — asadi-tools never became healthy" \
              && docker compose logs --tail=60 asadi-tools && exit 1
            sleep 5
          done

      - name: Prune old images
        if: success()
        run: docker image prune -f
