name: api-ci-deploy

on:
  push:
    branches: [master]
  workflow_dispatch:

jobs:
  test-build-deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - name: Build API image
        run: docker build -t cc-api-ci:${{ github.sha }} .

      - name: Configure SSH
        run: |
          mkdir -p ~/.ssh
          printf '%s\n' "${{ secrets.DEPLOY_SSH_PRIVATE_KEY }}" > ~/.ssh/deploy_key
          chmod 600 ~/.ssh/deploy_key
          printf '%s\n' "${{ secrets.DEPLOY_KNOWN_HOSTS }}" > ~/.ssh/known_hosts

      - name: Deploy API
        run: |
          ssh -i ~/.ssh/deploy_key "${{ secrets.DEPLOY_USER }}@${{ secrets.API_DEPLOY_HOST }}" '
            set -euo pipefail
            cd /home/kcar/api
            git fetch origin master
            git reset --hard origin/master
            docker network inspect kevlarai-network >/dev/null 2>&1 || docker network create kevlarai-network
            docker compose -p api -f docker-compose.yml up -d --build
            docker compose -p api -f docker-compose.yml ps
            curl -fsS http://127.0.0.1:8000/health >/dev/null
          '
