name: Deploy

on:
  push:
    branches: [main]
  workflow_dispatch:
    inputs:
      image_tag:
        description: Docker image tag to deploy
        required: false
        default: latest

jobs:
  build-and-push:
    name: Build & Push Docker image
    runs-on: ubuntu-latest

    permissions:
      contents: read
      packages: write

    outputs:
      image_tag: ${{ steps.meta.outputs.version }}

    steps:
      - uses: actions/checkout@v4

      - uses: pnpm/action-setup@v4
        with:
          version: 9

      - uses: actions/setup-node@v4
        with:
          node-version: 22
          cache: pnpm

      - name: Install dependencies
        run: pnpm install --frozen-lockfile

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

      - name: Log in to GitHub Container Registry
        uses: docker/login-action@v3
        with:
          registry: ghcr.io
          username: ${{ github.actor }}
          password: ${{ secrets.GITHUB_TOKEN }}

      - name: Docker metadata
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: ghcr.io/${{ github.repository }}/colectivo-web
          tags: |
            type=sha,prefix=,suffix=,format=short
            type=raw,value=latest,enable={{is_default_branch}}

      - name: Build and push
        uses: docker/build-push-action@v5
        with:
          context: .
          file: apps/web/Dockerfile
          push: true
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
          cache-from: type=gha
          cache-to: type=gha,mode=max
          build-args: |
            PUBLIC_SUPABASE_URL=${{ secrets.PUBLIC_SUPABASE_URL }}
            PUBLIC_SUPABASE_ANON_KEY=${{ secrets.PUBLIC_SUPABASE_ANON_KEY }}
            PUBLIC_KEYCLOAK_URL=${{ secrets.PUBLIC_KEYCLOAK_URL }}
            PUBLIC_KEYCLOAK_REALM=${{ secrets.PUBLIC_KEYCLOAK_REALM }}
            PUBLIC_KEYCLOAK_CLIENT_ID=${{ secrets.PUBLIC_KEYCLOAK_CLIENT_ID }}
            PUBLIC_APP_URL=${{ secrets.PUBLIC_APP_URL }}

  deploy:
    name: Deploy to production
    runs-on: ubuntu-latest
    needs: build-and-push
    environment: production

    steps:
      - uses: actions/checkout@v4

      - name: Setup SSH
        run: |
          mkdir -p ~/.ssh
          echo "${{ secrets.DEPLOY_SSH_KEY }}" > ~/.ssh/id_ed25519
          chmod 600 ~/.ssh/id_ed25519
          ssh-keyscan -H "${{ secrets.DEPLOY_HOST_IP }}" >> ~/.ssh/known_hosts

      - name: Deploy
        run: |
          IMAGE_TAG="${{ needs.build-and-push.outputs.image_tag }}" \
          DEPLOY_HOST="${{ secrets.DEPLOY_HOST }}" \
          DEPLOY_PATH="${{ secrets.DEPLOY_PATH }}" \
          bash infra/scripts/deploy.sh
