"""add ticket_checklist_items and ticket_drafts tables

Revision ID: chk001
Revises: usr001
Create Date: 2026-06-21

Tenant-schema migration. Adds:
  - ticket_checklist_items: persistent, tickable QA/action items per ticket
    (seeded by the AI "Check reply" pass or added manually).
  - ticket_drafts: per-user unsent reply drafts, keyed (ticket_id, user_id),
    so team members no longer overwrite each other's drafts.

Runs against the active tenant search_path (no explicit schema arg), the same
pattern as every other tenant-table migration. Guarded with has_table so it is
safe to run on schemas where the tables were already applied directly.
"""
from alembic import op
import sqlalchemy as sa

revision = 'chk001'
down_revision = 'usr001'
branch_labels = None
depends_on = None


def upgrade():
    insp = sa.inspect(op.get_bind())
    existing = set(insp.get_table_names())

    if 'ticket_checklist_items' not in existing:
        op.create_table(
            'ticket_checklist_items',
            sa.Column('id', sa.Integer, primary_key=True, autoincrement=True),
            sa.Column('ticket_id', sa.Integer, sa.ForeignKey('tickets.id'),
                      nullable=False, index=True),
            sa.Column('text', sa.Text, nullable=False),
            sa.Column('done', sa.Boolean, nullable=False, server_default='false'),
            sa.Column('source', sa.String(10), nullable=False, server_default='manual'),
            sa.Column('position', sa.Integer, nullable=False, server_default='0'),
            sa.Column('created_at', sa.DateTime, nullable=False,
                      server_default=sa.func.now()),
        )

    if 'ticket_drafts' not in existing:
        op.create_table(
            'ticket_drafts',
            sa.Column('ticket_id', sa.Integer, sa.ForeignKey('tickets.id'),
                      primary_key=True),
            sa.Column('user_id', sa.Integer, primary_key=True),
            sa.Column('body_html', sa.Text, nullable=True),
            sa.Column('updated_at', sa.DateTime, nullable=False,
                      server_default=sa.func.now()),
        )


def downgrade():
    op.drop_table('ticket_drafts')
    op.drop_table('ticket_checklist_items')
