name: Backup Verification

on:
  # Run weekly on Sundays at 05:00 UTC
  schedule:
    - cron: '0 5 * * 0'
  # Manual trigger
  workflow_dispatch:
    inputs:
      skip_cleanup:
        description: 'Keep test database for debugging'
        required: false
        default: 'false'
        type: choice
        options:
          - 'false'
          - 'true'

concurrency:
  group: backup-verify
  cancel-in-progress: false

jobs:
  verify-backup:
    name: Backup Restore Verification
    runs-on: ubuntu-latest
    timeout-minutes: 30

    services:
      postgres:
        image: postgis/postgis:16-3.4
        env:
          POSTGRES_DB: goodgo
          POSTGRES_USER: goodgo
          POSTGRES_PASSWORD: goodgo_ci_secret
        ports:
          - 5432:5432
        options: >-
          --health-cmd "pg_isready -U goodgo -d goodgo"
          --health-interval 10s
          --health-timeout 5s
          --health-retries 5
          --health-start-period 30s

    env:
      DATABASE_URL: postgresql://goodgo:goodgo_ci_secret@localhost:5432/goodgo
      PGHOST: localhost
      PGPORT: '5432'
      PGUSER: goodgo
      PGPASSWORD: goodgo_ci_secret
      PGDATABASE: goodgo

    steps:
      - uses: actions/checkout@v4

      - name: Setup Node.js
        uses: actions/setup-node@v4
        with:
          node-version: 22

      - name: Install pnpm
        uses: pnpm/action-setup@v4
        with:
          version: 10

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

      - name: Generate Prisma client
        run: pnpm db:generate

      - name: Run migrations
        run: pnpm db:migrate:dev

      - name: Seed database
        run: pnpm db:seed

      - name: Create backup
        run: |
          mkdir -p /tmp/backups
          pg_dump \
            -h localhost \
            -p 5432 \
            -U goodgo \
            -d goodgo \
            --no-owner \
            --no-privileges \
            --format=custom \
            --compress=6 \
            -f /tmp/backups/goodgo_ci_test.sql.gz

      - name: Run backup verification
        run: |
          chmod +x scripts/backup/pg-verify-backup.sh
          BACKUP_DIR=/tmp/backups \
          REPORT_FILE=/tmp/backups/verify-report.json \
          SKIP_CLEANUP=${{ github.event.inputs.skip_cleanup || 'false' }} \
            scripts/backup/pg-verify-backup.sh

      - name: Upload verification report
        if: always()
        uses: actions/upload-artifact@v4
        with:
          name: backup-verify-report
          path: /tmp/backups/verify-report.json
          retention-days: 30
