"""fix_oauth_installation_unique_constraint

Revision ID: 9a5b2c3d4e8h
Revises: 9a5b2c3d4e7g
Create Date: 2026-01-23

Fixes the unique constraint on oauth_app_installation table:
- Drops the old unique constraint on installation_id (now external_id)
- Creates a compound unique constraint on (provider, external_id)

This allows the same external_id to exist across different providers
(e.g., GitHub installation 12345 and GitLab installation 12345 can coexist).
"""

from typing import Sequence, Union

from alembic import op


# revision identifiers, used by Alembic.
revision: str = "9a5b2c3d4e8h"
down_revision: Union[str, None] = "9a5b2c3d4e7g"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    """Fix unique constraint for multi-provider OAuth support."""

    # Drop old unique constraint on installation_id (now external_id)
    # The constraint name is auto-generated by SQLAlchemy as "github_app_installation_installation_id_key"
    op.drop_constraint(
        "github_app_installation_installation_id_key",
        "oauth_app_installation",
        type_="unique",
    )

    # Create compound unique constraint on (provider, external_id)
    # This allows same external_id across different providers
    op.create_unique_constraint(
        "uq_oauth_app_installation_provider_external_id",
        "oauth_app_installation",
        ["provider", "external_id"],
    )


def downgrade() -> None:
    """Revert to single-column unique constraint."""

    # Drop compound unique constraint
    op.drop_constraint(
        "uq_oauth_app_installation_provider_external_id",
        "oauth_app_installation",
        type_="unique",
    )

    # Recreate old unique constraint on external_id only
    # Note: This will fail if there are duplicate external_ids across providers
    op.create_unique_constraint(
        "github_app_installation_installation_id_key",
        "oauth_app_installation",
        ["external_id"],
    )
