name: CI/CD Pipeline

on:
  push:
    branches:
      - main
      - develop

jobs:
  build:
    name: Build Docker Image
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v5.0.0

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

      - name: Test Docker image
        run: |
          docker run -d \
            --name go-app-test \
            -p 8080:8080 \
            go-app:${{ github.sha }}

          sleep 3

          curl --fail http://localhost:8080/health

          docker stop go-app-test
          docker rm go-app-test


  deploy-staging:
    name: Deploy to Staging
    needs: build
    if: github.ref == 'refs/heads/develop'
    runs-on: ubuntu-latest

    steps:
      - name: Checkout repository
        uses: actions/checkout@v5.0.0

      - 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 }}"

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


  deploy-production:
    name: Deploy to Production
    needs: build
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest

    environment:
      name: production

    steps:
      - name: Checkout repository
        uses: actions/checkout@v5.0.0

      - 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 }}"

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