name: Deploy

on:
  push:
    branches: ["main", "dev"]
  pull_request:
    branches: ["main", "dev"]

permissions:
  contents: read
  packages: write

jobs:
  build:
    name: Build
    runs-on: ubuntu-latest
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Install pnpm
        uses: pnpm/action-setup@v6

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: "24"
          cache: "pnpm"
          cache-dependency-path: "pnpm-lock.yaml"

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

      - name: Generate Prisma client
        run: pnpm --filter pp-backend run generate
        env:
          DATABASE_URL: postgresql://postgres:postgres@localhost:5432/pp

      - name: Build backend
        run: pnpm --filter pp-backend run build

      - name: Build frontend
        run: pnpm --filter pp-frontend run build

  docker:
    name: Build and Push Docker Image
    needs: build
    runs-on: ubuntu-latest
    if: github.event_name == 'push' && (github.ref == 'refs/heads/main' || github.ref == 'refs/heads/dev')
    steps:
      - name: Checkout repository
        uses: actions/checkout@v4

      - name: Setup Buildx
        uses: docker/setup-buildx-action@v3

      - name: Generate image metadata
        id: meta
        uses: docker/metadata-action@v5
        with:
          images: registry.reversed.dev/pp-previews/core
          tags: |
            type=raw,value=prod,enable=${{ github.event_name == 'push' && github.ref == 'refs/heads/main' }}
            type=raw,value=latest,enable=${{ github.event_name == 'push' && github.ref == 'refs/heads/main' }}
            type=raw,value=dev,enable=${{ github.event_name == 'push' && github.ref == 'refs/heads/dev' }}
            type=sha,format=long,enable=${{ github.event_name == 'push' }}
          labels: |
            org.opencontainers.image.title=PR Previews
            org.opencontainers.image.description=Self-hosted Gitea PR preview environments on EC2
            org.opencontainers.image.vendor=space

      - name: Log in to Harbor
        uses: docker/login-action@v3
        with:
          registry: registry.reversed.dev
          username: ${{ secrets.HARBOR_USERNAME }}
          password: ${{ secrets.HARBOR_PASSWORD }}

      - name: Build image
        uses: docker/build-push-action@v6
        with:
          context: .
          push: true
          provenance: false
          sbom: false
          tags: ${{ steps.meta.outputs.tags }}
          labels: ${{ steps.meta.outputs.labels }}
