name: Docker API

on:
  push:
    branches: [main]
    paths:
      - 'src/food-market.api/**'
      - 'src/food-market.application/**'
      - 'src/food-market.domain/**'
      - 'src/food-market.infrastructure/**'
      - 'src/food-market.shared/**'
      - 'deploy/Dockerfile.api'
      - 'deploy/docker-compose.yml'
      - '.forgejo/workflows/docker-api.yml'
      - 'food-market.sln'
  workflow_dispatch:

env:
  LOCAL_REGISTRY: 127.0.0.1:5001

jobs:
  build:
    name: Build + push API
    runs-on: [self-hosted, linux]
    steps:
      - uses: actions/checkout@v4

      - name: Build + push (Docker daemon layer-cache)
        env:
          SHA: ${{ github.sha }}
          DOCKER_BUILDKIT: '1'
        run: |
          # Используем обычный docker build — у host docker daemon в
          # /etc/docker/daemon.json уже прописан 127.0.0.1:5001 как
          # insecure-registry, и docker layer-cache между сборками
          # дает быстрый dotnet restore/pnpm install при стабильных манифестах.
          docker build \
            -f deploy/Dockerfile.api \
            -t $LOCAL_REGISTRY/food-market-api:$SHA \
            -t $LOCAL_REGISTRY/food-market-api:latest \
            .
          docker push $LOCAL_REGISTRY/food-market-api:$SHA
          docker push $LOCAL_REGISTRY/food-market-api:latest

  deploy:
    name: Deploy API on stage
    needs: build
    runs-on: [self-hosted, linux]
    steps:
      - uses: actions/checkout@v4

      - name: Update compose + .env
        env:
          PGPASS: ${{ secrets.STAGE_POSTGRES_PASSWORD }}
        run: |
          # Стенд использует :latest для обоих сервисов, .env переписываем
          # идемпотентно — без затирания тэга соседнего сервиса.
          cat > /home/nns/food-market-stage/deploy/.env <<ENV
          REGISTRY=127.0.0.1:5001
          API_TAG=latest
          WEB_TAG=latest
          POSTGRES_PASSWORD=$PGPASS
          ENV
          cp deploy/docker-compose.yml /home/nns/food-market-stage/deploy/docker-compose.yml

      - name: Pull + recreate api only
        working-directory: /home/nns/food-market-stage/deploy
        run: |
          docker compose pull api
          docker compose up -d --no-deps api

      - name: Smoke /health
        run: |
          for i in 1 2 3 4 5 6; do
            sleep 5
            if curl -fsS http://127.0.0.1:8080/health | grep -q '"status":"ok"'; then
              echo "Health OK"
              exit 0
            fi
          done
          echo "Health failed"
          exit 1

      - name: Notify Telegram on success
        if: success()
        env:
          BOT: ${{ secrets.TELEGRAM_BOT_TOKEN }}
          CHAT: ${{ secrets.TELEGRAM_CHAT_ID }}
          SHA: ${{ github.sha }}
        run: |
          curl -sS -X POST "https://api.telegram.org/bot$BOT/sendMessage" \
            --data-urlencode "chat_id=$CHAT" \
            --data-urlencode "text=✅ stage api deployed — ${SHA:0:7} → https://food-market.zat.kz" \
            > /dev/null

      - name: Notify Telegram on failure
        if: failure()
        env:
          BOT: ${{ secrets.TELEGRAM_BOT_TOKEN }}
          CHAT: ${{ secrets.TELEGRAM_CHAT_ID }}
          SHA: ${{ github.sha }}
        run: |
          curl -sS -X POST "https://api.telegram.org/bot$BOT/sendMessage" \
            --data-urlencode "chat_id=$CHAT" \
            --data-urlencode "text=❌ stage api deploy FAILED — ${SHA:0:7}" \
            > /dev/null
