name: Migration Safety

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

jobs:
  migration-safety:
    name: Alembic upgrade/downgrade safety
    runs-on: ubuntu-latest

    services:
      postgres:
        image: postgres:16
        env:
          POSTGRES_DB: nexapg
          POSTGRES_USER: nexapg
          POSTGRES_PASSWORD: nexapg
        ports:
          - 5432:5432
        options: >-
          --health-cmd "pg_isready -U nexapg -d nexapg"
          --health-interval 5s
          --health-timeout 5s
          --health-retries 30

    env:
      DB_HOST: postgres
      DB_PORT: 5432
      DB_NAME: nexapg
      DB_USER: nexapg
      DB_PASSWORD: nexapg
      JWT_SECRET_KEY: ci-jwt-secret-key
      ENCRYPTION_KEY: MDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDA=

    steps:
      - name: Checkout
        uses: actions/checkout@v4

      - name: Set up Python
        uses: actions/setup-python@v5
        with:
          python-version: "3.12"

      - name: Install backend dependencies
        run: pip install -r backend/requirements.txt

      - name: Install PostgreSQL client tools
        run: sudo apt-get update && sudo apt-get install -y postgresql-client

      - name: Wait for PostgreSQL
        env:
          PGPASSWORD: nexapg
        run: |
          for i in $(seq 1 60); do
            if pg_isready -h postgres -p 5432 -U nexapg -d nexapg; then
              exit 0
            fi
            sleep 2
          done
          echo "PostgreSQL did not become ready in time."
          exit 1

      - name: Alembic upgrade -> downgrade -1 -> upgrade
        working-directory: backend
        run: |
          alembic upgrade head
          alembic downgrade -1
          alembic upgrade head

      - name: Validate schema consistency after roundtrip
        env:
          PGPASSWORD: nexapg
        run: |
          cd backend
          alembic upgrade head
          pg_dump -h postgres -p 5432 -U nexapg -d nexapg --schema-only --no-owner --no-privileges \
            | sed '/^\\restrict /d; /^\\unrestrict /d' > /tmp/schema_head_before.sql

          alembic downgrade -1
          alembic upgrade head
          pg_dump -h postgres -p 5432 -U nexapg -d nexapg --schema-only --no-owner --no-privileges \
            | sed '/^\\restrict /d; /^\\unrestrict /d' > /tmp/schema_head_after.sql

          diff -u /tmp/schema_head_before.sql /tmp/schema_head_after.sql
