"""Add oauth grant type

Revision ID: 530415194e90
Revises: 67914e68c877
Create Date: 2025-07-01 15:10:31.252754

"""

from collections.abc import Sequence

import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

from alembic import op

# revision identifiers, used by Alembic.
revision: str = "530415194e90"
down_revision: str | None = "67914e68c877"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    sa.Enum("AUTHORIZATION_CODE", "CLIENT_CREDENTIALS", name="oauthgranttype").create(
        op.get_bind()
    )
    op.add_column(
        "oauth_integration",
        sa.Column(
            "grant_type",
            postgresql.ENUM(
                "AUTHORIZATION_CODE",
                "CLIENT_CREDENTIALS",
                name="oauthgranttype",
                create_type=False,
            ),
            nullable=False,
            # Up until this point, all integrations were created with authorization code grant type
            server_default=sa.text("'AUTHORIZATION_CODE'"),
        ),
    )
    # Remove the server default to force explicit values for new rows
    op.alter_column("oauth_integration", "grant_type", server_default=None)
    op.drop_constraint(
        "uq_oauth_integration_owner_provider", "oauth_integration", type_="unique"
    )
    op.create_unique_constraint(
        "uq_oauth_integration_owner_provider_user_flow",
        "oauth_integration",
        ["owner_id", "provider_id", "user_id", "grant_type"],
    )
    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_constraint(
        "uq_oauth_integration_owner_provider_user_flow",
        "oauth_integration",
        type_="unique",
    )
    op.create_unique_constraint(
        "uq_oauth_integration_owner_provider",
        "oauth_integration",
        ["owner_id", "provider_id"],
        postgresql_nulls_not_distinct=False,
    )
    op.drop_column("oauth_integration", "grant_type")
    sa.Enum("AUTHORIZATION_CODE", "CLIENT_CREDENTIALS", name="oauthgranttype").drop(
        op.get_bind()
    )
    # ### end Alembic commands ###
