name: Production Deploy

on:
  push:
    branches: [main]

env:
  REGISTRY: ghcr.io
  GH_USER: therealowenrees
  IMAGE_NAME: therealowenrees/chess-pdf-api:latest

jobs:
  publish:
    name: publish image
    runs-on: ubuntu-24.04

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

      - name: Login to Github Container Registry
        run: echo "${{ secrets.GHCR_SECRET }}" | docker login ghcr.io -u ${{ env.GH_USER }} --password-stdin

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

      - name: Build image and publish with Cache
        uses: docker/build-push-action@v5
        with:
          context: .
          push: true
          tags: ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
          cache-from: type=gha
          cache-to: type=gha,mode=max

  deploy:
    needs: publish
    name: deploy image
    runs-on: ubuntu-24.04

    steps:
      - name: Connect and pull image from GHCR
        uses: appleboy/ssh-action@v1.2.5
        with:
          host: ${{ secrets.HOST }}
          username: ${{ secrets.USERNAME }}
          key: ${{ secrets.SSH_KEY }}
          port: ${{ secrets.PORT }}
          script: |
            cd /home/${{ secrets.USERNAME }}
            echo "${{ secrets.GHCR_SECRET }}" | docker login ghcr.io -u ${{ env.GH_USER }} --password-stdin
            docker pull ${{ env.REGISTRY }}/${{ env.IMAGE_NAME }}
            docker compose up -d
