# .gitea/workflows/manual-db-backup.yml
#
# This workflow provides a manual trigger to back up the production database.
# It creates a compressed SQL dump and saves it as a downloadable artifact.
name: Manual - Backup Production Database

on:
  workflow_dispatch:
    inputs:
      confirmation:
        description: 'Type "backup-production-db" to confirm you want to create a backup.'
        required: true
        default: 'do-not-run'

jobs:
  backup-database:
    runs-on: projectium.com # This job runs on your self-hosted Gitea runner.

    env:
      # Use production database credentials for this entire job.
      DB_HOST: ${{ secrets.DB_HOST }}
      DB_PORT: ${{ secrets.DB_PORT }}
      DB_USER: ${{ secrets.DB_USER }}
      DB_PASSWORD: ${{ secrets.DB_PASSWORD }}
      DB_NAME: ${{ secrets.DB_NAME_PROD }}

    steps:
      - name: Validate Secrets
        run: |
          if [ -z "$DB_HOST" ] || [ -z "$DB_USER" ] || [ -z "$DB_PASSWORD" ] || [ -z "$DB_NAME" ]; then
            echo "ERROR: One or more production database secrets are not set in Gitea repository settings."
            exit 1
          fi
          echo "✅ All required database secrets are present."

      - name: Verify Confirmation Phrase
        run: |
          if [ "${{ gitea.event.inputs.confirmation }}" != "backup-production-db" ]; then
            echo "ERROR: Confirmation phrase did not match. Aborting database backup."
            exit 1
          fi
          echo "✅ Confirmation accepted. Proceeding with database backup."

      - name: Create Database Backup
        id: backup
        run: |
          # Generate a timestamped filename for the backup.
          TIMESTAMP=$(date +'%Y%m%d-%H%M%S')
          BACKUP_FILENAME="flyer-crawler-prod-backup-${TIMESTAMP}.sql.gz"
          echo "Creating backup file: $BACKUP_FILENAME"

          # Use pg_dump to create a plain-text SQL dump, then pipe it to gzip for compression.
          # This is more efficient than creating a large uncompressed file first.
          PGPASSWORD="$DB_PASSWORD" pg_dump -h "$DB_HOST" -p "$DB_PORT" -U "$DB_USER" -d "$DB_NAME" --clean --if-exists | gzip > "$BACKUP_FILENAME"

          echo "✅ Database backup created successfully."
          echo "backup_filename=$BACKUP_FILENAME" >> $GITEA_ENV

      - name: Upload Backup as Artifact
        uses: actions/upload-artifact@v3
        with:
          name: database-backup
          path: ${{ env.backup_filename }}
