name: Preview

on:
  pull_request:
    types:
      - opened
      - reopened
      - synchronize
      - closed
    branches:
      - main
      - dev

jobs:
  apply:
    runs-on: ubuntu-latest
    env:
      SUPABASE_ACCESS_TOKEN: ${{ secrets.SUPABASE_ACCESS_TOKEN }}
      TF_VAR_linked_project: ${{ github.base_ref == 'main' && secrets.PRODUCTION_PROJECT_ID || secrets.STAGING_PROJECT_ID }}
      TF_VAR_git_branch: ${{ github.head_ref }}
      TF_CLI_ARGS_apply: -target=supabase_settings.preview
    defaults:
      run:
        working-directory: packages/core/supabase/remotes
    outputs:
      db_user: ${{ steps.branch.outputs.user }}
      db_pass: ${{ steps.branch.outputs.password }}
      db_host: ${{ steps.branch.outputs.host }}
      db_port: ${{ steps.branch.outputs.port }}
      jwt_secret: ${{ steps.branch.outputs.jwt_secret }}
      ref: ${{ steps.branch.outputs.id }}
      status: ${{ steps.branch.outputs.status }}
      version: ${{ steps.branch.outputs.version }}

    steps:
      - uses: actions/checkout@v4
      - uses: hashicorp/setup-terraform@v3
        with:
          terraform_wrapper: false

      - run: terraform init
      - run: terraform apply -auto-approve -no-color
      - id: branch
        run: |
          terraform output -json branch_database \
          | jq -r "to_entries|map(\"\(.key)=\(.value|tostring)\")|.[]" \
          >> "$GITHUB_OUTPUT"

      - if: github.event.action == 'closed'
        run: terraform apply -auto-approve -no-color -destroy

  migrate:
    needs: apply
    runs-on: ubuntu-latest
    if: github.event.action != 'closed'
    env:
      SUPABASE_ACCESS_TOKEN: ${{ secrets.SUPABASE_ACCESS_TOKEN }}
      SUPABASE_DB_PASSWORD: ${{ needs.apply.outputs.db_pass }}

    steps:
      - uses: actions/checkout@v4
      - uses: supabase/setup-cli@v1
        with:
          version: latest

      - uses: nick-fields/retry@v3
        with:
          timeout_seconds: 15
          max_attempts: 10
          command: supabase link --project-ref ${{ needs.apply.outputs.ref }}

      # This is your quality firewall check
      - name: 🛠️ Validate Migrations, RLS, and Functions
        run: yes | supabase db reset --linked
        working-directory: packages/core
