name: CI/CD - Build & Deploy to Ghaymah Cloud

on:
  push:
    branches:
      - develop
      - main

jobs:
  # ==========================================================
  # Build & Smoke Test
  # ==========================================================
  build-and-test:
    runs-on: ubuntu-latest

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

      - name: Build Docker image
        run: |
          docker build -t exam-api:${{ github.sha }} .

      - name: Smoke Test
        run: |
          docker run -d -p 5000:5000 --name smoke-test exam-api:${{ github.sha }}
          sleep 8
          curl -f http://localhost:5000/health
          docker stop smoke-test
          docker rm smoke-test

  # ==========================================================
  # Deploy Staging
  # ==========================================================
  deploy-staging:
    if: github.ref == 'refs/heads/develop'

    needs: build-and-test

    runs-on: ubuntu-latest

    environment: staging

    steps:
      - uses: actions/checkout@v5

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

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

      - name: Use Staging Config
        run: |
          cp .ghaymah.staging.json .ghaymah.json

      - name: Deploy to Staging
        run: |
          $HOME/ghaymah/bin/gy resource app launch

  # ==========================================================
  # Deploy Production
  # ==========================================================
  deploy-production:
    if: github.ref == 'refs/heads/main'

    needs: build-and-test

    runs-on: ubuntu-latest

    environment: production

    steps:
      - uses: actions/checkout@v5

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

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

      - name: Use Production Config
        run: |
          cp .ghaymah.production.json .ghaymah.json

      - name: Deploy to Production
        run: |
          $HOME/ghaymah/bin/gy resource app launch
