name: Build, Deploy & Monitor Ghaymah Application

on:
  push:
    branches:
      - main
      - develop

  workflow_dispatch:

env:
  APP_DIR: ./task1-deploy

jobs:

  build:
    name: Build & Validate Docker Image
    runs-on: ubuntu-latest

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

      - name: Build Docker image
        run: |
          docker build \
            -t training-api:${{ github.sha }} \
            ${{ env.APP_DIR }}

      - name: Run container
        run: |
          docker run -d \
            --name test-container \
            -p 8080:8080 \
            training-api:${{ github.sha }}

      - name: Health Check
        run: |
          sleep 5
          curl -f http://localhost:8080/health

      - name: Cleanup
        if: always()
        run: |
          docker stop test-container || true
          docker rm test-container || true

  deploy-staging:
    name: Deploy to Staging
    needs: build
    runs-on: ubuntu-latest

    environment:
      name: staging

    steps:
      - uses: actions/checkout@v4

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

      # حسب الوثائق الرسمية
      - name: Authenticate
        run: |
          echo "Login using: gy auth login"

      - name: Launch Application
        working-directory: task1-deploy
        run: |
          gy resource app launch

      - name: Smoke Test
        run: |
          sleep 20
          curl -f https://task1-deploy-aee3d4210e10.hosted.ghaymah.systems/health

  approve-production:
    name: Manual Approval
    needs: deploy-staging
    runs-on: ubuntu-latest

    environment:
      name: production-approval

    steps:
      - run: echo "Waiting for manual approval"

  deploy-production:
    name: Deploy Production
    needs: approve-production
    runs-on: ubuntu-latest

    environment:
      name: production

    steps:
      - uses: actions/checkout@v4

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

      - name: Authenticate
        run: |
          echo "Login using: gy auth login"

      - name: Launch Application
        working-directory: task1-deploy
        run: |
          gy resource app launch

      - name: Production Health Check
        run: |
          sleep 20
          curl -f https://task1-deploy-aee3d4210e10.hosted.ghaymah.systems/health
