name: Build Check

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

jobs:
  build:
    runs-on: ubuntu-latest
    env:
      DATABASE_URL: "postgresql://fake:fake@localhost:5432/fake?schema=public"

    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'

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

      - name: Build Next.js app
        run: pnpm run build
  
  push-image:
    needs: build
    runs-on: ubuntu-latest
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'
    steps:
      - name: checkout
        uses: actions/checkout@v4

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

      - 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 and push image
        uses: docker/build-push-action@v6
        with:
          context: .
          push: true
          provenance: false
          sbom: false
          tags: |
            registry.reversed.dev/my-portfolio/my-portfolio:latest
            registry.reversed.dev/my-portfolio/my-portfolio:${{ github.sha }}

  deploy-coolify:
    needs: push-image
    runs-on: ubuntu-latest
    if: github.event_name == 'push' && github.ref == 'refs/heads/main'
    steps:
      - name: wait 5 seconds before redeploy
        run: sleep 5

      - name: Redeploy Coolify
        run: |
          response_file="$(mktemp)"
          http_code="$(curl -sS -o "$response_file" -w "%{http_code}" -X GET "${{ secrets.COOLIFY_WEBHOOK }}" \
            -H "Authorization: Bearer ${{ secrets.COOLIFY_TOKEN }}")"

          echo "Coolify webhook HTTP status: $http_code"
          echo "Coolify webhook response body:"
          cat "$response_file"

          if [ "$http_code" -lt 200 ] || [ "$http_code" -ge 300 ]; then
            echo "Redeploy request failed with non-2xx status."
            exit 1
          fi