"""add teacher help cards

Revision ID: 0016_teacher_help_cards
Revises: 0015_growth_profiles
"""

from alembic import context, op
import sqlalchemy as sa


revision = "0016_teacher_help_cards"
down_revision = "0015_growth_profiles"
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_teacher_help_card" in tables:
        return
    op.create_table(
        "sys_teacher_help_card",
        sa.Column("id", PRIMARY_KEY_TYPE, primary_key=True, autoincrement=True),
        sa.Column("user_id", sa.BigInteger(), sa.ForeignKey("sys_user.id"), nullable=False),
        sa.Column("topic_session_id", sa.BigInteger(), sa.ForeignKey("sys_topic_session.id"), nullable=False),
        sa.Column("summary_id", sa.BigInteger(), nullable=True),
        sa.Column("content", sa.Text(), nullable=False),
        sa.Column("source", sa.String(30), nullable=False, server_default="topic_summary"),
        sa.Column("copied", sa.Integer(), nullable=False, server_default="0"),
        sa.Column("copied_at", sa.DateTime(), nullable=True),
        sa.Column("created_at", sa.DateTime(), server_default=sa.func.now(), nullable=False),
    )
    op.create_index("ix_sys_teacher_help_card_user_id", "sys_teacher_help_card", ["user_id"])
    op.create_index("ix_sys_teacher_help_card_summary_id", "sys_teacher_help_card", ["summary_id"])
    op.create_index("ix_sys_teacher_help_card_user_created", "sys_teacher_help_card", ["user_id", "created_at"])
    op.create_index("ix_sys_teacher_help_card_topic_created", "sys_teacher_help_card", ["topic_session_id", "created_at"])


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