name: CI

on:
  pull_request:
    branches: [master]
  push:
    branches: [master]
  workflow_dispatch:

jobs:
  test:
    runs-on: ubuntu-latest

    services:
      postgres:
        image: postgres:17
        env:
          POSTGRES_USER: polaris
          POSTGRES_PASSWORD: polaris
          POSTGRES_DB: polaris
        ports:
          - 5432:5432
        options: >-
          --health-cmd "pg_isready -U polaris"
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5

    env:
      DATABASE_URL: postgres://polaris:polaris@localhost:5432/polaris_test

    steps:
      - uses: actions/checkout@v4

      - uses: oven-sh/setup-bun@v2
        with:
          bun-version: latest

      - run: bun install

      - name: Create test database
        run: PGPASSWORD=polaris psql -h localhost -U polaris -d polaris -c "CREATE DATABASE polaris_test OWNER polaris;"

      - run: bun test

  deploy:
    needs: test
    runs-on: ubuntu-latest
    if: github.ref == 'refs/heads/master' && github.event_name == 'push'
    concurrency:
      group: production-deploy
      cancel-in-progress: false

    steps:
      - name: Deploy to production
        env:
          DEPLOY_SSH_KEY: ${{ secrets.DEPLOY_SSH_KEY }}
        run: |
          mkdir -p ~/.ssh
          echo "$DEPLOY_SSH_KEY" > ~/.ssh/deploy_key
          chmod 600 ~/.ssh/deploy_key
          ssh-keyscan -H withpolaris.ai >> ~/.ssh/known_hosts
          ssh -i ~/.ssh/deploy_key deploy@withpolaris.ai "
            cd /opt/polaris &&
            git pull --ff-only &&
            docker compose -f docker-compose.prod.yml build &&
            docker compose -f docker-compose.prod.yml up -d --remove-orphans &&
            docker compose -f docker-compose.prod.yml restart caddy &&
            docker compose -f docker-compose.prod.yml ps
          "
