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:
    client_api_key_status = sa.Enum(
        "active",
        "deprecated",
        "expired",
        name="client_api_key_status",
    )
    client_api_key_status.create(op.get_bind(), checkfirst=True)

    op.add_column(
        "client_api_keys",
        sa.Column(
            "status",
            client_api_key_status,
            server_default="active",
            nullable=False,
        ),
    )
    op.add_column(
        "client_api_keys",
        sa.Column(
            "rotated_at",
            sa.DateTime,
            nullable=True,
        ),
    )
    op.add_column(
        "client_api_keys",
        sa.Column(
            "expires_at",
            sa.DateTime,
            nullable=True,
        ),
    )
    op.add_column(
        "client_api_keys",
        sa.Column(
            "created_at",
            sa.DateTime,
            server_default=sa.text("timezone('Asia/Tokyo', now())"),
            nullable=False,
        ),
    )
    op.add_column(
        "client_api_keys",
        sa.Column(
            "updated_at",
            sa.DateTime,
            server_default=sa.text("timezone('Asia/Tokyo', now())"),
            nullable=False,
        ),
    )


def downgrade() -> None:
    op.drop_column("client_api_keys", "updated_at", if_exists=True)
    op.drop_column("client_api_keys", "created_at", if_exists=True)
    op.drop_column("client_api_keys", "expires_at", if_exists=True)
    op.drop_column("client_api_keys", "rotated_at", if_exists=True)
    op.drop_column("client_api_keys", "status", if_exists=True)
    op.execute("DROP TYPE IF EXISTS client_api_key_status CASCADE")
