"""auto renewal events

Revision ID: 051_auto_renew_events
Revises: 050_expiry_reminders
Create Date: 2026-06-20
"""

import sqlalchemy as sa
from alembic import op


revision = "051_auto_renew_events"
down_revision = "050_expiry_reminders"
branch_labels = None
depends_on = None


def _table_names(bind) -> set[str]:
    return set(sa.inspect(bind).get_table_names())


def upgrade() -> None:
    bind = op.get_bind()
    tables = _table_names(bind)

    if "auto_renewal_events" not in tables:
        op.create_table(
            "auto_renewal_events",
            sa.Column("event_key", sa.String(length=160), nullable=False),
            sa.Column("user_id", sa.BigInteger(), nullable=False),
            sa.Column("instance_id", sa.Integer(), nullable=False),
            sa.Column("order_id", sa.Integer(), nullable=True),
            sa.Column("status", sa.String(length=24), nullable=False, server_default=sa.text("'processing'")),
            sa.Column("cycles", sa.Integer(), nullable=False, server_default=sa.text("1")),
            sa.Column("amount_cents", sa.Integer(), nullable=False, server_default=sa.text("0")),
            sa.Column("old_expires_at", sa.DateTime(timezone=True), nullable=False),
            sa.Column("new_expires_at", sa.DateTime(timezone=True), nullable=True),
            sa.Column("error_code", sa.String(length=64), nullable=True),
            sa.Column("message", sa.String(length=255), nullable=True),
            sa.Column("processed_at", sa.DateTime(timezone=True), nullable=True),
            sa.Column("id", sa.Integer(), autoincrement=True, nullable=False),
            sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
            sa.Column("updated_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
            sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"),
            sa.ForeignKeyConstraint(["instance_id"], ["instances.id"], ondelete="CASCADE"),
            sa.ForeignKeyConstraint(["order_id"], ["orders.id"], ondelete="SET NULL"),
            sa.PrimaryKeyConstraint("id"),
            sa.UniqueConstraint("event_key", name="uq_auto_renewal_events_event_key"),
        )
        op.create_index("ix_auto_renewal_events_user_id", "auto_renewal_events", ["user_id"])
        op.create_index("ix_auto_renewal_events_instance_id", "auto_renewal_events", ["instance_id"])
        op.create_index("ix_auto_renewal_events_order_id", "auto_renewal_events", ["order_id"])
        op.create_index("ix_auto_renewal_events_status", "auto_renewal_events", ["status"])


def downgrade() -> None:
    bind = op.get_bind()
    tables = _table_names(bind)

    if "auto_renewal_events" in tables:
        op.drop_table("auto_renewal_events")
