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", "whi_customer_id", existing_type=sa.ARRAY(sa.Text), nullable=True)
    op.alter_column("tenants", "cydas_customer_id", existing_type=sa.ARRAY(sa.Text), nullable=True)

    op.execute("UPDATE tenants SET whi_customer_id = NULL WHERE whi_customer_id = '{}'")
    op.execute("UPDATE tenants SET cydas_customer_id = NULL WHERE cydas_customer_id = '{}'")


def downgrade() -> None:
    op.execute("UPDATE tenants SET whi_customer_id = ARRAY[]::text[] WHERE whi_customer_id IS NULL")
    op.execute("UPDATE tenants SET cydas_customer_id = ARRAY[]::text[] WHERE cydas_customer_id IS NULL")
    # 初期出荷の定義と同一
    op.alter_column("tenants", "whi_customer_id", existing_type=sa.ARRAY(sa.Text), nullable=False)
    op.alter_column("tenants", "cydas_customer_id", existing_type=sa.ARRAY(sa.Text), nullable=True)
