"""Add auth_provider table

Revision ID: a1b2c3d4e5f6
Revises: 75e709e9d355
Create Date: 2025-01-27 12:00:00.000000

"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql


# revision identifiers, used by Alembic.
revision = 'a1b2c3d4e5f6'
down_revision = '75e709e9d355'
branch_labels = None
depends_on = None


def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    # First add AUTH_PROVIDER to the integrationType enum if not exists
    op.execute("ALTER TYPE integrationtype ADD VALUE IF NOT EXISTS 'AUTH_PROVIDER'")

    # Check if authtype enum exists, if not create it
    op.execute("""
        DO $$ BEGIN
            CREATE TYPE authtype AS ENUM (
                'oauth2', 'oauth2_with_refresh', 'oauth2_with_refresh_rotating',
                'api_key', 'native_functionality', 'config_class', 'trello_auth',
                'none'
            );
        EXCEPTION
            WHEN duplicate_object THEN null;
        END $$;
    """)

    # Create auth_provider table using existing enum
    op.create_table(
        'auth_provider',
        sa.Column('name', sa.String(), nullable=False),
        sa.Column('short_name', sa.String(), nullable=False),
        sa.Column('class_name', sa.String(), nullable=False),
        sa.Column('auth_config_class', sa.String(), nullable=False),
        sa.Column('config_class', sa.String(), nullable=False),
        sa.Column('auth_type', postgresql.ENUM(name='authtype', create_type=False), nullable=False),
        sa.Column('description', sa.Text(), nullable=True),
        sa.Column('organization_id', sa.UUID(), nullable=True),
        sa.Column('id', sa.UUID(), nullable=False),
        sa.Column('created_at', sa.DateTime(), nullable=False),
        sa.Column('modified_at', sa.DateTime(), nullable=False),
        sa.ForeignKeyConstraint(['organization_id'], ['organization.id'], ),
        sa.PrimaryKeyConstraint('id'),
        sa.UniqueConstraint('name', 'organization_id', name='uq_auth_provider_name_org'),
        sa.UniqueConstraint('short_name')
    )
    # ### end Alembic commands ###


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('auth_provider')

    # Note: PostgreSQL doesn't support removing enum values easily
    # We'll leave AUTH_PROVIDER in the enum as removing it requires recreating the entire enum
    # ### end Alembic commands ###
