name: Deploy To Ghaymah

permissions:
  contents: read

concurrency:
  group: oudelaa-production-${{ github.ref }}
  cancel-in-progress: true

on:
  pull_request:
    branches:
      - main
  push:
    branches:
      - main

jobs:
  quality:
    runs-on: ubuntu-latest
    services:
      mongodb:
        image: mongo:7
        ports:
          - 27017:27017
        options: >-
          --health-cmd "mongosh --quiet --eval 'db.runCommand({ ping: 1 })'"
          --health-interval 10s
          --health-timeout 5s
          --health-retries 10
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Use Node.js 20
        uses: actions/setup-node@v4
        with:
          node-version: 20
          cache: npm

      - name: Install locked dependencies
        run: npm ci

      - name: Static quality gates
        run: |
          npm run lint
          npm run build

      - name: Unit, integration, and coverage gates
        run: npm run test:coverage

      - name: Upload coverage report
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: coverage-report
          path: coverage/
          if-no-files-found: error
          retention-days: 14

      - name: Performance tooling tests
        run: npm run test:perf

      - name: End-to-end tests
        run: npm run test:e2e
        env:
          E2E_MONGODB_URI: mongodb://127.0.0.1:27017/oudelaa-e2e

      - name: Dependency security audit
        run: npm audit --audit-level=high

      - name: Verify production image
        run: docker build --tag oudelaa-api:${{ github.sha }} .

  deploy:
    needs: quality
    runs-on: ubuntu-latest
    environment: production

    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Create .ghaymah.json
        run: |
          cat > .ghaymah.json << 'EOF'
          {
            "id": "da97e2b8-0b2c-49d8-a672-1d162c8e15f1",
            "name": "oudelaa-api",
            "projectId": "1137d5bd-c997-4654-9d01-3c7a88b07269",
            "ports": [
              {
                "expose": true,
                "number": 4000
              }
            ],
            "publicAccess": {
              "enabled": true
            },
            "resourceTier": "g1.nano",
            "dockerFileName": "Dockerfile"
          }
          EOF

          cat .ghaymah.json

      - name: Install Ghaymah CLI
        run: curl -sSl https://cli.ghaymah.systems/install.sh | bash

      - name: Login to Ghaymah
        run: |
          $HOME/ghaymah/bin/gy auth login \
            --email "${{ secrets.GHAYMAH_EMAIL }}" \
            --password "${{ secrets.GHAYMAH_PW }}" \
            --no-auto-update

      - name: Deploy
        run: $HOME/ghaymah/bin/gy resource app launch --no-auto-update
