"""introduce composed primary key for secrets table

Revision ID: 7e5d82221765
Revises: db5cf73c0869
Create Date: 2024-11-05 10:52:24.394416

"""

from typing import Sequence, Union

from alembic import op
import sqlmodel  # noqa F401


# revision identifiers, used by Alembic.
revision: str = "7e5d82221765"
down_revision: Union[str, None] = "db5cf73c0869"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###

    op.execute("""
        ALTER TABLE secrets
        DROP CONSTRAINT secrets_pkey,
        ADD PRIMARY KEY (secret_id, user_id)
    """)

    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###

    conn = op.get_bind()

    # Check for duplicates first
    result = conn.execute(
        sqlmodel.text("""
        SELECT COUNT(*) 
        FROM (
            SELECT secret_id
            FROM secrets
            GROUP BY secret_id
            HAVING COUNT(*) > 1
        ) as duplicates
    """)
    )
    duplicate_count = result.scalar()

    if duplicate_count > 0:
        raise Exception(
            "Cannot downgrade: Multiple secrets exist with the same secret_id"
        )

    op.execute("""
        ALTER TABLE secrets
        DROP CONSTRAINT secrets_pkey,
        ADD PRIMARY KEY (secret_id)
    """)

    # ### end Alembic commands ###
