name: app-ci-deploy

on:
  push:
    branches: [master]
  workflow_dispatch:

jobs:
  test-build-deploy:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - uses: actions/setup-node@v4
        with:
          node-version: '20'
          cache: npm
      - run: npm ci
      - run: npm run test:run
      - run: npm run build

      - 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 app
        run: |
          ssh -i ~/.ssh/deploy_key "${{ secrets.DEPLOY_USER }}@${{ secrets.APP_DEPLOY_HOST }}" '
            set -euo pipefail
            cd /home/kcar/app
            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 app-prod -f docker-compose.yml up -d --build
            docker compose -p app-prod -f docker-compose.yml ps
            curl -fsSI http://127.0.0.1:3000 >/dev/null
          '
