"""add autoresponse_templates and addons_messages.is_auto_response

Tenant-schema migration. Adds:
  - autoresponse_templates: the org's out-of-office auto-response template
    (is_active marks the live row; mode is 'static' or
    'ai_with_static_fallback').
  - addons_messages.is_auto_response: flags outbound messages that were sent
    automatically by the auto-response feature (vs a human reply).

Runs against the active tenant search_path (no explicit schema arg), the same
pattern as every other tenant-table migration.

Revision ID: ar002
Revises: ar001
Create Date: 2026-07-14
"""
from alembic import op
import sqlalchemy as sa

revision = 'ar002'
down_revision = 'ar001'
branch_labels = None
depends_on = None


def _column_exists(conn, table, column):
    return conn.execute(sa.text(
        "SELECT 1 FROM information_schema.columns "
        "WHERE table_schema = current_schema() AND table_name = :t AND column_name = :c"
    ), {"t": table, "c": column}).fetchone() is not None


def _in_public_schema(conn):
    """True when this migration is running against the public schema.

    autoresponse_templates and addons_messages.is_auto_response are per-tenant
    objects — they must never be created in public. run_tenant_migrations.py
    runs the public pass through the same linear chain, so this migration must
    no-op there (mirrors how the public schema is stamped past tenant tables).
    """
    return conn.execute(sa.text("SELECT current_schema()")).scalar() == 'public'


def upgrade():
    conn = op.get_bind()
    if _in_public_schema(conn):
        return
    insp = sa.inspect(conn)
    existing = set(insp.get_table_names())

    if 'autoresponse_templates' not in existing:
        op.create_table(
            'autoresponse_templates',
            sa.Column('id', sa.Integer, primary_key=True, autoincrement=True),
            sa.Column('is_active', sa.Boolean, nullable=False, server_default='false'),
            sa.Column('mode', sa.String(30), nullable=False, server_default='static'),
            sa.Column('body_html', sa.Text, nullable=False),
            sa.Column('subject_filter', sa.Text, nullable=True),
            sa.Column('created_at', sa.DateTime, nullable=False,
                      server_default=sa.func.now()),
            sa.Column('updated_at', sa.DateTime, nullable=False,
                      server_default=sa.func.now()),
        )

    if not _column_exists(conn, 'addons_messages', 'is_auto_response'):
        op.add_column(
            'addons_messages',
            sa.Column('is_auto_response', sa.Boolean(), nullable=False, server_default='false'),
        )


def downgrade():
    conn = op.get_bind()
    if _in_public_schema(conn):
        return
    op.drop_column('addons_messages', 'is_auto_response')
    op.drop_table('autoresponse_templates')
