name: Deploy to Staging

on:
  workflow_dispatch:
    inputs:
      image_tag:
        description: "Docker image tag to deploy (commit SHA, staging, or v*)"
        required: true
        default: "staging"
        type: string

env:
  APP_IMAGE: git.koppkb.com/KoPKB/api_arrahn
  DEPLOY_DIR: /home/arrahn/Project/api_arrahn

jobs:
  deploy:
    runs-on: host

    steps:
      - name: Checkout repository
        uses: actions/checkout@v4
        with:
          ref: ${{ inputs.image_tag }}

      - name: Login to Docker registry
        run: |
          echo "${{ secrets.REGISTRY_PASSWORD }}" | \
            docker login git.koppkb.com \
              -u "${{ secrets.REGISTRY_USERNAME }}" \
              --password-stdin

      - name: Verify image exists in registry
        run: |
          set -e
          IMAGE_TAG="${{ inputs.image_tag }}"
          IMAGE="${APP_IMAGE}:${IMAGE_TAG}"

          echo "Checking if image exists: ${IMAGE}"
          if ! docker manifest inspect "${IMAGE}" > /dev/null 2>&1; then
            echo "ERROR: Image ${IMAGE} does not exist in registry!"
            echo "Run the Build Docker Image workflow first."
            exit 1
          fi
          echo "✓ ${IMAGE} found"

      - name: Pull Docker image
        run: |
          set -e
          IMAGE_TAG="${{ inputs.image_tag }}"
          docker pull "${APP_IMAGE}:${IMAGE_TAG}"
          echo "✓ Image pulled successfully"

      - name: Sync compose file and deploy
        run: |
          set -e
          IMAGE_TAG="${{ inputs.image_tag }}"

          mkdir -p "${DEPLOY_DIR}/docker/nginx" "${DEPLOY_DIR}/docker/mysql"
          cp docker-compose.staging.yml "${DEPLOY_DIR}/docker-compose.yml"
          cp docker/nginx/default.conf "${DEPLOY_DIR}/docker/nginx/default.conf"
          cp -R docker/mysql/init "${DEPLOY_DIR}/docker/mysql/"

          if [ ! -f "${DEPLOY_DIR}/.env.staging" ]; then
            if [ -f .env.staging ]; then
              cp .env.staging "${DEPLOY_DIR}/.env.staging"
              echo "Copied .env.staging from repo (first deploy). Edit ${DEPLOY_DIR}/.env.staging on the server if needed."
            else
              echo "ERROR: ${DEPLOY_DIR}/.env.staging is missing on the server"
              exit 1
            fi
          fi

          cd "${DEPLOY_DIR}"

          export APP_IMAGE
          export IMAGE_TAG

          docker compose --env-file .env.staging -f docker-compose.yml pull app
          docker compose --env-file .env.staging -f docker-compose.yml up -d --no-build --remove-orphans

          echo "✓ Deployed IMAGE_TAG=${IMAGE_TAG}"

      - name: Verify deployment
        run: |
          set -e
          cd "${DEPLOY_DIR}"

          echo "Waiting for services to start..."
          sleep 10

          for SERVICE in app web mysql; do
            STATUS=$(docker compose --env-file .env.staging -f docker-compose.yml ps --status running --format '{{.Name}}' "$SERVICE" 2>/dev/null || true)
            if [ -z "$STATUS" ]; then
              echo "ERROR: ${SERVICE} is not running"
              docker compose --env-file .env.staging -f docker-compose.yml ps
              docker compose --env-file .env.staging -f docker-compose.yml logs --tail=50 "$SERVICE" || true
              exit 1
            fi
            echo "✓ ${SERVICE} is running (${STATUS})"
          done

          HTTP_PORT=$(grep -E '^HTTP_PORT=' .env.staging 2>/dev/null | cut -d= -f2- | tr -d '"' || true)
          HTTP_PORT=${HTTP_PORT:-8090}

          check_health() {
            NAME=$1
            URL=$2
            for i in 1 2 3 4 5 6; do
              if curl -sf "$URL" > /dev/null; then
                echo "✓ ${NAME} health check passed (${URL})"
                return 0
              fi
              echo "Waiting for ${NAME}... attempt ${i}/6"
              sleep 5
            done
            echo "ERROR: ${NAME} health check failed (${URL})"
            docker compose --env-file .env.staging -f docker-compose.yml logs --tail=50 app web || true
            return 1
          }

          check_health "api" "http://127.0.0.1:${HTTP_PORT}/health"
