"""notification expiry reminders

Revision ID: 050_expiry_reminders
Revises: 049_notification_enhancements
Create Date: 2026-06-20
"""

import sqlalchemy as sa
from alembic import op


revision = "050_expiry_reminders"
down_revision = "049_notification_enhancements"
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 "notification_events" not in tables:
        op.create_table(
            "notification_events",
            sa.Column("event_key", sa.String(length=160), nullable=False),
            sa.Column("event_type", sa.String(length=64), nullable=False),
            sa.Column("user_id", sa.BigInteger(), nullable=False),
            sa.Column("resource_type", sa.String(length=32), nullable=False),
            sa.Column("resource_id", sa.BigInteger(), nullable=False),
            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.PrimaryKeyConstraint("id"),
            sa.UniqueConstraint("event_key", name="uq_notification_events_event_key"),
        )
        op.create_index("ix_notification_events_event_type", "notification_events", ["event_type"])
        op.create_index("ix_notification_events_user_id", "notification_events", ["user_id"])
        op.create_index("ix_notification_events_resource_type", "notification_events", ["resource_type"])
        op.create_index("ix_notification_events_resource_id", "notification_events", ["resource_id"])


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

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