name: PR Preview
on:
  pull_request:
    types: [opened, synchronize, reopened, closed]

jobs:
  test:
    if: github.event.action != 'closed'
    runs-on: test
    steps:
      - uses: actions/checkout@v4
      - name: Build check
        run: cd frontend && npm ci && npm run build

  deploy-preview:
    if: github.event.action != 'closed'
    needs: test
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Deploy Preview
        run: python3 scripts/deploy-preview.py deploy ${{ github.event.pull_request.number }}
      - name: Comment PR
        env:
          GIT_TOKEN: ${{ secrets.GIT_TOKEN }}
        run: |
          PR_ID="${{ github.event.pull_request.number }}"
          curl -sf -X POST \
            "https://git.euphon.cloud/api/v1/repos/${{ github.repository }}/issues/${PR_ID}/comments" \
            -H "Authorization: token ${GIT_TOKEN}" \
            -H "Content-Type: application/json" \
            -d "{\"body\": \"🚀 **Preview**: https://pr-${PR_ID}.planner.oci.euphon.net\n\nDB is a copy of production.\"}" || true

  teardown-preview:
    if: github.event.action == 'closed'
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Teardown
        run: python3 scripts/deploy-preview.py teardown ${{ github.event.pull_request.number }}
      - name: Comment PR
        env:
          GIT_TOKEN: ${{ secrets.GIT_TOKEN }}
        run: |
          PR_ID="${{ github.event.pull_request.number }}"
          curl -sf -X POST \
            "https://git.euphon.cloud/api/v1/repos/${{ github.repository }}/issues/${PR_ID}/comments" \
            -H "Authorization: token ${GIT_TOKEN}" \
            -H "Content-Type: application/json" \
            -d "{\"body\": \"🗑️ Preview torn down.\"}" || true
