name: Deploy stage

on:
  workflow_run:
    workflows: ["Docker Images"]
    types: [completed]
    branches: [main]
  workflow_dispatch:

concurrency:
  group: deploy-stage
  cancel-in-progress: false

jobs:
  deploy:
    name: docker compose pull + up
    runs-on: ubuntu-latest
    if: ${{ github.event.workflow_run.conclusion == 'success' || github.event_name == 'workflow_dispatch' }}
    steps:
      - uses: actions/checkout@v4

      - name: Add SSH key
        run: |
          mkdir -p ~/.ssh
          echo "${{ secrets.STAGE_SSH_KEY }}" > ~/.ssh/id_ed25519
          chmod 600 ~/.ssh/id_ed25519
          ssh-keyscan -p ${{ secrets.STAGE_SSH_PORT }} -H ${{ secrets.STAGE_SSH_HOST }} >> ~/.ssh/known_hosts 2>/dev/null

      - name: Copy compose files
        run: |
          SSH="ssh -p ${{ secrets.STAGE_SSH_PORT }} ${{ secrets.STAGE_SSH_USER }}@${{ secrets.STAGE_SSH_HOST }}"
          SCP="scp -P ${{ secrets.STAGE_SSH_PORT }}"
          $SSH 'mkdir -p ~/food-market-stage/deploy'
          $SCP deploy/docker-compose.yml ${{ secrets.STAGE_SSH_USER }}@${{ secrets.STAGE_SSH_HOST }}:~/food-market-stage/deploy/
          $SCP deploy/nginx.conf ${{ secrets.STAGE_SSH_USER }}@${{ secrets.STAGE_SSH_HOST }}:~/food-market-stage/deploy/

      - name: Write .env (tags + port overrides)
        run: |
          SSH="ssh -p ${{ secrets.STAGE_SSH_PORT }} ${{ secrets.STAGE_SSH_USER }}@${{ secrets.STAGE_SSH_HOST }}"
          SHA="${{ github.event.workflow_run.head_sha || github.sha }}"
          $SSH "cat > ~/food-market-stage/deploy/.env" <<ENV
          REGISTRY=127.0.0.1:5001
          API_TAG=$SHA
          WEB_TAG=$SHA
          POSTGRES_PASSWORD=${{ secrets.STAGE_POSTGRES_PASSWORD }}
          ENV

      - name: Login to ghcr on stage
        run: |
          SSH="ssh -p ${{ secrets.STAGE_SSH_PORT }} ${{ secrets.STAGE_SSH_USER }}@${{ secrets.STAGE_SSH_HOST }}"
          $SSH "echo '${{ secrets.GITHUB_TOKEN }}' | docker login ghcr.io -u ${{ github.actor }} --password-stdin"

      - name: Pull + up (stage compose)
        id: deploy
        run: |
          SSH="ssh -p ${{ secrets.STAGE_SSH_PORT }} ${{ secrets.STAGE_SSH_USER }}@${{ secrets.STAGE_SSH_HOST }}"
          $SSH 'cd ~/food-market-stage/deploy && docker compose pull && docker compose up -d --remove-orphans'

      - name: Smoke test /health
        run: |
          SSH="ssh -p ${{ secrets.STAGE_SSH_PORT }} ${{ secrets.STAGE_SSH_USER }}@${{ secrets.STAGE_SSH_HOST }}"
          for i in 1 2 3 4 5 6; do
            sleep 5
            if $SSH "curl -fsS http://localhost:8080/health" 2>&1 | tee /tmp/health.out | grep -q '"status":"ok"'; then
              echo "Health OK"
              exit 0
            fi
          done
          echo "Health failed"
          cat /tmp/health.out || true
          exit 1

      - name: Notify Telegram on success
        if: success()
        run: |
          curl -sS -X POST "https://api.telegram.org/bot${{ secrets.TELEGRAM_BOT_TOKEN }}/sendMessage" \
            --data-urlencode "chat_id=${{ secrets.TELEGRAM_CHAT_ID }}" \
            --data-urlencode "text=Deploy stage OK — commit ${GITHUB_SHA:0:7}. http://88.204.171.93:8081" \
            > /dev/null

      - name: Notify Telegram on failure
        if: failure()
        run: |
          curl -sS -X POST "https://api.telegram.org/bot${{ secrets.TELEGRAM_BOT_TOKEN }}/sendMessage" \
            --data-urlencode "chat_id=${{ secrets.TELEGRAM_CHAT_ID }}" \
            --data-urlencode "text=Deploy stage FAILED — commit ${GITHUB_SHA:0:7}. See https://github.com/${{ github.repository }}/actions/runs/${{ github.run_id }}" \
            > /dev/null
