"""add_whatsapp_business_tables

Revision ID: whatsapp001
Revises: 359991e24ea2
Create Date: 2025-11-13 12:00:00.000000+01:00

"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

# revision identifiers, used by Alembic.
revision: str = 'whatsapp001'
down_revision: Union[str, None] = '359991e24ea2'
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # Create ENUMs using raw SQL to avoid double-creation issues
    conn = op.get_bind()

    # Create WhatsApp message status enum if it doesn't exist
    conn.execute(sa.text("""
        DO $$ BEGIN
            CREATE TYPE whatsappmessagestatus AS ENUM ('PENDING', 'SENT', 'DELIVERED', 'READ', 'FAILED');
        EXCEPTION
            WHEN duplicate_object THEN null;
        END $$;
    """))

    # Create WhatsApp message type enum if it doesn't exist
    conn.execute(sa.text("""
        DO $$ BEGIN
            CREATE TYPE whatsappmessagetype AS ENUM ('TEMPLATE', 'TEXT', 'IMAGE', 'DOCUMENT', 'INTERACTIVE');
        EXCEPTION
            WHEN duplicate_object THEN null;
        END $$;
    """))

    # Create whatsapp_messages table
    op.create_table(
        'whatsapp_messages',
        sa.Column('id', sa.UUID(), nullable=False),
        sa.Column('tenant_id', sa.UUID(), nullable=False),
        sa.Column('notification_id', sa.UUID(), nullable=True),
        sa.Column('whatsapp_message_id', sa.String(length=255), nullable=True),
        sa.Column('recipient_phone', sa.String(length=20), nullable=False),
        sa.Column('recipient_name', sa.String(length=255), nullable=True),
        sa.Column('message_type', postgresql.ENUM('TEMPLATE', 'TEXT', 'IMAGE', 'DOCUMENT', 'INTERACTIVE', name='whatsappmessagetype', create_type=False), nullable=False),
        sa.Column('status', postgresql.ENUM('PENDING', 'SENT', 'DELIVERED', 'READ', 'FAILED', name='whatsappmessagestatus', create_type=False), nullable=False),
        sa.Column('template_name', sa.String(length=255), nullable=True),
        sa.Column('template_language', sa.String(length=10), nullable=True),
        sa.Column('template_parameters', postgresql.JSON(astext_type=sa.Text()), nullable=True),
        sa.Column('message_body', sa.Text(), nullable=True),
        sa.Column('media_url', sa.String(length=512), nullable=True),
        sa.Column('sent_at', sa.DateTime(), nullable=True),
        sa.Column('delivered_at', sa.DateTime(), nullable=True),
        sa.Column('read_at', sa.DateTime(), nullable=True),
        sa.Column('failed_at', sa.DateTime(), nullable=True),
        sa.Column('error_code', sa.String(length=50), nullable=True),
        sa.Column('error_message', sa.Text(), nullable=True),
        sa.Column('provider_response', postgresql.JSON(astext_type=sa.Text()), nullable=True),
        sa.Column('additional_data', postgresql.JSON(astext_type=sa.Text()), nullable=True),
        sa.Column('conversation_id', sa.String(length=255), nullable=True),
        sa.Column('conversation_category', sa.String(length=50), nullable=True),
        sa.Column('created_at', sa.DateTime(), nullable=False),
        sa.Column('updated_at', sa.DateTime(), nullable=False),
        sa.PrimaryKeyConstraint('id')
    )

    # Create indexes for whatsapp_messages
    op.create_index(op.f('ix_whatsapp_messages_tenant_id'), 'whatsapp_messages', ['tenant_id'], unique=False)
    op.create_index(op.f('ix_whatsapp_messages_notification_id'), 'whatsapp_messages', ['notification_id'], unique=False)
    op.create_index(op.f('ix_whatsapp_messages_whatsapp_message_id'), 'whatsapp_messages', ['whatsapp_message_id'], unique=False)
    op.create_index(op.f('ix_whatsapp_messages_recipient_phone'), 'whatsapp_messages', ['recipient_phone'], unique=False)
    op.create_index(op.f('ix_whatsapp_messages_status'), 'whatsapp_messages', ['status'], unique=False)
    op.create_index(op.f('ix_whatsapp_messages_conversation_id'), 'whatsapp_messages', ['conversation_id'], unique=False)
    op.create_index(op.f('ix_whatsapp_messages_created_at'), 'whatsapp_messages', ['created_at'], unique=False)

    # Create composite indexes for common queries
    op.create_index('idx_whatsapp_tenant_status', 'whatsapp_messages', ['tenant_id', 'status'], unique=False)
    op.create_index('idx_whatsapp_tenant_created', 'whatsapp_messages', ['tenant_id', 'created_at'], unique=False)

    # Drop existing whatsapp_templates table if it exists (schema change)
    # This drops the old schema version from the initial migration
    conn.execute(sa.text("DROP TABLE IF EXISTS whatsapp_templates CASCADE"))

    # Create whatsapp_templates table with new schema
    op.create_table(
        'whatsapp_templates',
        sa.Column('id', sa.UUID(), nullable=False),
        sa.Column('tenant_id', sa.UUID(), nullable=True),
        sa.Column('template_name', sa.String(length=255), nullable=False),
        sa.Column('template_key', sa.String(length=100), nullable=False),
        sa.Column('display_name', sa.String(length=255), nullable=False),
        sa.Column('description', sa.Text(), nullable=True),
        sa.Column('category', sa.String(length=50), nullable=False),
        sa.Column('language', sa.String(length=10), nullable=True),
        sa.Column('status', sa.String(length=20), nullable=True),
        sa.Column('header_type', sa.String(length=20), nullable=True),
        sa.Column('header_text', sa.String(length=60), nullable=True),
        sa.Column('body_text', sa.Text(), nullable=False),
        sa.Column('footer_text', sa.String(length=60), nullable=True),
        sa.Column('parameters', postgresql.JSON(astext_type=sa.Text()), nullable=True),
        sa.Column('parameter_count', sa.Integer(), nullable=True),
        sa.Column('buttons', postgresql.JSON(astext_type=sa.Text()), nullable=True),
        sa.Column('is_active', sa.Boolean(), nullable=True),
        sa.Column('is_system', sa.Boolean(), nullable=True),
        sa.Column('sent_count', sa.Integer(), nullable=True),
        sa.Column('last_used_at', sa.DateTime(), nullable=True),
        sa.Column('whatsapp_template_id', sa.String(length=255), nullable=True),
        sa.Column('approved_at', sa.DateTime(), nullable=True),
        sa.Column('rejected_at', sa.DateTime(), nullable=True),
        sa.Column('rejection_reason', sa.Text(), nullable=True),
        sa.Column('created_at', sa.DateTime(), nullable=False),
        sa.Column('updated_at', sa.DateTime(), nullable=False),
        sa.PrimaryKeyConstraint('id'),
        sa.UniqueConstraint('template_key')
    )

    # Create indexes for whatsapp_templates
    op.create_index(op.f('ix_whatsapp_templates_tenant_id'), 'whatsapp_templates', ['tenant_id'], unique=False)
    op.create_index(op.f('ix_whatsapp_templates_template_name'), 'whatsapp_templates', ['template_name'], unique=False)


def downgrade() -> None:
    # Drop tables
    op.drop_index(op.f('ix_whatsapp_templates_template_name'), table_name='whatsapp_templates', if_exists=True)
    op.drop_index(op.f('ix_whatsapp_templates_tenant_id'), table_name='whatsapp_templates', if_exists=True)
    op.drop_table('whatsapp_templates', if_exists=True)

    op.drop_index('idx_whatsapp_tenant_created', table_name='whatsapp_messages', if_exists=True)
    op.drop_index('idx_whatsapp_tenant_status', table_name='whatsapp_messages', if_exists=True)
    op.drop_index(op.f('ix_whatsapp_messages_created_at'), table_name='whatsapp_messages', if_exists=True)
    op.drop_index(op.f('ix_whatsapp_messages_conversation_id'), table_name='whatsapp_messages', if_exists=True)
    op.drop_index(op.f('ix_whatsapp_messages_status'), table_name='whatsapp_messages', if_exists=True)
    op.drop_index(op.f('ix_whatsapp_messages_recipient_phone'), table_name='whatsapp_messages', if_exists=True)
    op.drop_index(op.f('ix_whatsapp_messages_whatsapp_message_id'), table_name='whatsapp_messages', if_exists=True)
    op.drop_index(op.f('ix_whatsapp_messages_notification_id'), table_name='whatsapp_messages', if_exists=True)
    op.drop_index(op.f('ix_whatsapp_messages_tenant_id'), table_name='whatsapp_messages', if_exists=True)
    op.drop_table('whatsapp_messages', if_exists=True)

    # Drop enums if they exist
    conn = op.get_bind()

    result = conn.execute(sa.text(
        "SELECT 1 FROM pg_type WHERE typname = 'whatsappmessagetype'"
    ))
    if result.fetchone():
        conn.execute(sa.text("DROP TYPE whatsappmessagetype"))

    result = conn.execute(sa.text(
        "SELECT 1 FROM pg_type WHERE typname = 'whatsappmessagestatus'"
    ))
    if result.fetchone():
        conn.execute(sa.text("DROP TYPE whatsappmessagestatus"))
