name: Deploy to Production

on:
  push:
    branches: [main]

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

jobs:
  deploy:
    runs-on: ubuntu-latest

    steps:
      - name: Validate deploy target
        run: |
          if [ -z "${{ secrets.DEPLOY_HOST }}" ]; then
            echo "::error::DEPLOY_HOST secret is not set"
            exit 1
          fi

      - name: Setup SSH
        run: |
          mkdir -p ~/.ssh
          echo "${{ secrets.DEPLOY_SSH_KEY }}" > ~/.ssh/deploy_key
          chmod 600 ~/.ssh/deploy_key
          echo "${{ secrets.DEPLOY_HOST }} ${{ secrets.DEPLOY_HOST_KEY }}" >> ~/.ssh/known_hosts

      - name: Deploy via SSH
        env:
          HOST: ${{ secrets.DEPLOY_HOST }}
        run: |
          ssh -o ServerAliveInterval=15 -o ServerAliveCountMax=3 -o ConnectTimeout=30 -i ~/.ssh/deploy_key root@$HOST << 'DEPLOY'
            set -e
            cd /opt/icp-tracker

            echo "=== Pulling latest code ==="
            git fetch origin main
            git reset --hard origin/main

            echo "=== Building and starting containers ==="
            docker compose up -d --build

            echo "=== Cleaning up old images ==="
            docker image prune -af --filter "until=24h"

            echo "=== Deploy complete ==="
          DEPLOY

      - name: Health check
        run: |
          echo "Waiting for services to become healthy..."
          for i in $(seq 1 6); do
            WEB=$(curl -sfm 10 "https://icp.sitehub.cloud/" > /dev/null 2>&1 && echo "OK" || echo "FAIL")
            AUTH=$(curl -sfm 10 "https://icp.sitehub.cloud/api/auth/ok" > /dev/null 2>&1 && echo "OK" || echo "FAIL")
            echo "Attempt $i/6 — Web: $WEB, Auth: $AUTH"
            if [ "$WEB" = "OK" ]; then
              echo "All health checks passed"
              exit 0
            fi
            sleep 10
          done
          echo "::error::Health check failed after 6 attempts"
          exit 1

      - name: Log deployment
        if: always()
        run: |
          echo "::notice::Deployed ${{ github.sha }} to icp.sitehub.cloud by ${{ github.actor }} at $(date -u +%Y-%m-%dT%H:%M:%SZ) — status: ${{ job.status }}"
