from collections.abc import Sequence
from pathlib import Path

import sqlalchemy as sa
from alembic import op


def get_revision() -> str:
    return Path(__file__).name.split("-")[0]


def get_down_revision() -> str | None:
    versions_path = Path(__file__).parent
    migration_files = sorted([f.name for f in versions_path.iterdir() if f.is_file()])
    for i, file in enumerate(migration_files):
        if file == Path(__file__).name:
            return None if i == 0 else migration_files[i - 1].split("-")[0]
    return None


# revision identifiers, used by Alembic.
revision: str = get_revision()
down_revision: str | None = get_down_revision()
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def upgrade() -> None:
    op.alter_column(
        "tenants",
        "application_client_id",
        new_column_name="m2m_application_client_id",
        existing_type=sa.String(length=50),
    )
    op.add_column(
        "tenants",
        sa.Column("name", sa.String(length=255), nullable=True, unique=True),
        if_not_exists=True,
    )
    op.add_column(
        "tenants",
        sa.Column("user_application_client_id", sa.String(length=50), nullable=True, unique=True),
        if_not_exists=True,
    )
    # カラム名変更に伴うユニーク制約のリネーム
    op.execute(
        "ALTER TABLE tenants "
        "RENAME CONSTRAINT tenants_application_client_id_key TO tenants_m2m_application_client_id_key",
    )


def downgrade() -> None:
    op.execute(
        "ALTER TABLE tenants "
        "RENAME CONSTRAINT tenants_m2m_application_client_id_key TO tenants_application_client_id_key",
    )
    op.drop_column("tenants", "name", if_exists=True)
    op.drop_column("tenants", "user_application_client_id", if_exists=True)
    op.alter_column(
        "tenants",
        "m2m_application_client_id",
        new_column_name="application_client_id",
        existing_type=sa.String(length=50),
    )
