"""services phase 4A renewal before expiry due dates

Revision ID: 20260505_renewal_before_expiry_due_dates
Revises: 20260504_due_date_engine_foundation
Create Date: 2026-05-05
"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


revision: str = "20260505_renewal_before_expiry_due_dates"
down_revision: Union[str, None] = "20260504_due_date_engine_foundation"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def _insp():
    return sa.inspect(op.get_bind())


def _has_table(table_name: str) -> bool:
    return table_name in _insp().get_table_names()


def _has_column(table_name: str, column_name: str) -> bool:
    if not _has_table(table_name):
        return False
    return any(c["name"] == column_name for c in _insp().get_columns(table_name))


def _has_index(table_name: str, index_name: str) -> bool:
    if not _has_table(table_name):
        return False
    return any(ix.get("name") == index_name for ix in _insp().get_indexes(table_name))


def upgrade() -> None:
    if _has_table("service_due_date_rules") and not _has_column("service_due_date_rules", "renewal_days_before_expiry"):
        op.add_column("service_due_date_rules", sa.Column("renewal_days_before_expiry", sa.Integer(), nullable=True))

    if _has_table("client_service_subscriptions") and not _has_column("client_service_subscriptions", "expiry_date"):
        op.add_column("client_service_subscriptions", sa.Column("expiry_date", sa.Date(), nullable=True))

    if _has_table("client_service_subscriptions") and not _has_index("client_service_subscriptions", "ix_client_service_subscriptions_expiry_date"):
        op.create_index("ix_client_service_subscriptions_expiry_date", "client_service_subscriptions", ["expiry_date"])


def downgrade() -> None:
    if _has_table("client_service_subscriptions") and _has_index("client_service_subscriptions", "ix_client_service_subscriptions_expiry_date"):
        op.drop_index("ix_client_service_subscriptions_expiry_date", table_name="client_service_subscriptions")
    if _has_table("client_service_subscriptions") and _has_column("client_service_subscriptions", "expiry_date"):
        op.drop_column("client_service_subscriptions", "expiry_date")
    if _has_table("service_due_date_rules") and _has_column("service_due_date_rules", "renewal_days_before_expiry"):
        op.drop_column("service_due_date_rules", "renewal_days_before_expiry")
