name: CI/CD - Build, Push to Ghaymah Registry, Deploy

on:
  push:
    branches:
      - develop   # staging
      - main      # production
  workflow_dispatch: {}

env:
  GHAYMAH_REGISTRY: registry.ghaymah.systems
  IMAGE_NAME: motazelalfy/ghyma-cicd-demo

jobs:
  build-and-push:
    name: Build & Push Docker Image
    runs-on: ubuntu-latest
    outputs:
      image_tag: ${{ steps.vars.outputs.image_tag }}
    steps:
      - name: Checkout code
        uses: actions/checkout@v4

      - name: Set image tag (short commit SHA)
        id: vars
        run: echo "image_tag=$(echo $GITHUB_SHA | cut -c1-7)" >> "$GITHUB_OUTPUT"

      - name: Set up Docker Buildx
        uses: docker/setup-buildx-action@v3

      - name: Log in to Ghaymah Container Registry
        uses: docker/login-action@v3
        with:
          registry: ${{ env.GHAYMAH_REGISTRY }}
          username: ${{ secrets.GHAYMAH_REGISTRY_USERNAME }}
          password: ${{ secrets.GHAYMAH_REGISTRY_TOKEN }}

      - name: Build and push image
        uses: docker/build-push-action@v5
        with:
          context: .
          push: true
          tags: |
            ${{ env.GHAYMAH_REGISTRY }}/${{ env.IMAGE_NAME }}:${{ steps.vars.outputs.image_tag }}
            ${{ env.GHAYMAH_REGISTRY }}/${{ env.IMAGE_NAME }}:latest

  deploy-staging:
    name: Deploy to Staging
    needs: build-and-push
    if: github.ref == 'refs/heads/develop'
    runs-on: ubuntu-latest
    environment:
      name: staging
      url: https://staging-ghyma-demo.ghaymah.systems
    steps:
      - name: Install Ghaymah CLI
        run: |
          curl -fsSL https://cli.ghaymah.systems/install.sh | sh
          ghaymah --version

      - name: Authenticate with Ghaymah
        run: ghaymah login --token "${{ secrets.GHAYMAH_API_TOKEN }}"

      - name: Deploy image to staging
        run: |
          ghaymah deploy \
            --app ghyma-cicd-demo-staging \
            --image ${{ env.GHAYMAH_REGISTRY }}/${{ env.IMAGE_NAME }}:${{ needs.build-and-push.outputs.image_tag }} \
            --env staging

  deploy-production:
    name: Deploy to Production (manual approval required)
    needs: build-and-push
    if: github.ref == 'refs/heads/main'
    runs-on: ubuntu-latest
    environment:
      name: production
      url: https://ghyma-demo.ghaymah.systems
    steps:
      - name: Install Ghaymah CLI
        run: |
          curl -fsSL https://cli.ghaymah.systems/install.sh | sh
          ghaymah --version

      - name: Authenticate with Ghaymah
        run: ghaymah login --token "${{ secrets.GHAYMAH_API_TOKEN }}"

      - name: Deploy image to production
        run: |
          ghaymah deploy \
            --app ghyma-cicd-demo-production \
            --image ${{ env.GHAYMAH_REGISTRY }}/${{ env.IMAGE_NAME }}:${{ needs.build-and-push.outputs.image_tag }} \
            --env production
