"""add versioned content generation configs

Revision ID: 0027_content_generation
Revises: 0026_entitlement_renewal
"""

from __future__ import annotations

from alembic import context, op
import sqlalchemy as sa


revision = "0027_content_generation"
down_revision = "0026_entitlement_renewal"
branch_labels = None
depends_on = None

PRIMARY_KEY_TYPE = sa.BigInteger().with_variant(sa.Integer(), "sqlite")


def upgrade() -> None:
    inspector = None if context.is_offline_mode() else sa.inspect(op.get_bind())
    tables = set() if inspector is None else set(inspector.get_table_names())
    if "sys_content_generation_config" not in tables:
        op.create_table(
            "sys_content_generation_config",
            sa.Column("id", PRIMARY_KEY_TYPE, primary_key=True, autoincrement=True),
            sa.Column("config_type", sa.String(length=30), nullable=False),
            sa.Column("template_content", sa.Text(), nullable=False),
            sa.Column("instruction_content", sa.Text(), nullable=False),
            sa.Column("change_type", sa.String(length=20), nullable=False, server_default="save"),
            sa.Column("source_config_id", sa.BigInteger(), nullable=True),
            sa.Column("updated_by", sa.BigInteger(), nullable=True),
            sa.Column("updated_at", sa.DateTime(), server_default=sa.func.now(), nullable=False),
        )
        op.create_index(
            "ix_content_generation_type_updated",
            "sys_content_generation_config",
            ["config_type", "updated_at", "id"],
        )


def downgrade() -> None:
    inspector = None if context.is_offline_mode() else sa.inspect(op.get_bind())
    tables = {"sys_content_generation_config"} if inspector is None else set(inspector.get_table_names())
    if "sys_content_generation_config" not in tables:
        return
    op.drop_index("ix_content_generation_type_updated", table_name="sys_content_generation_config")
    op.drop_table("sys_content_generation_config")
