"""add share drafts

Revision ID: 0017_share_drafts
Revises: 0016_teacher_help_cards
"""

from alembic import context, op
import sqlalchemy as sa


revision = "0017_share_drafts"
down_revision = "0016_teacher_help_cards"
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_share_draft" in tables:
        return
    op.create_table(
        "sys_share_draft",
        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_share_draft_user_id", "sys_share_draft", ["user_id"])
    op.create_index("ix_sys_share_draft_summary_id", "sys_share_draft", ["summary_id"])
    op.create_index("ix_sys_share_draft_user_created", "sys_share_draft", ["user_id", "created_at"])
    op.create_index("ix_sys_share_draft_topic_created", "sys_share_draft", ["topic_session_id", "created_at"])


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