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.drop_column("clients", "parent_service")

    op.drop_constraint("uq_client_tenants_name_parent_service", "client_tenants", type_="unique")
    op.drop_column("client_tenants", "parent_service")

    op.add_column("client_tenants", sa.Column("client_id", sa.UUID, nullable=True))
    op.create_foreign_key(
        "fk_client_tenants_client_id_clients",
        "client_tenants",
        "clients",
        ["client_id"],
        ["id"],
    )
    op.create_unique_constraint(
        "uq_client_tenants_name_client_id",
        "client_tenants",
        ["name", "client_id"],
    )
    op.create_index(
        "uq_client_tenants_name_when_client_id_null",
        "client_tenants",
        ["name"],
        unique=True,
        postgresql_where=sa.text("client_id IS NULL"),
    )


def downgrade() -> None:
    op.drop_index("uq_client_tenants_name_when_client_id_null", table_name="client_tenants")
    op.drop_constraint("uq_client_tenants_name_client_id", "client_tenants", type_="unique")
    op.drop_constraint("fk_client_tenants_client_id_clients", "client_tenants", type_="foreignkey")
    op.drop_column("client_tenants", "client_id")

    op.add_column("client_tenants", sa.Column("parent_service", sa.String(64), nullable=True))
    op.create_unique_constraint(
        "uq_client_tenants_name_parent_service",
        "client_tenants",
        ["name", "parent_service"],
    )

    op.add_column("clients", sa.Column("parent_service", sa.String(64), nullable=True, default="ctm"))
