"""add recall webhook events

Revision ID: 20260515_0003
Revises: 20260514_0002
Create Date: 2026-05-15 00:00:00
"""
from __future__ import annotations

from alembic import op
import sqlalchemy as sa


revision = "20260515_0003"
down_revision = "20260514_0002"
branch_labels = None
depends_on = None


def upgrade() -> None:
    bind = op.get_bind()
    inspector = sa.inspect(bind)

    if "recall_webhook_events" not in inspector.get_table_names():
        op.create_table(
            "recall_webhook_events",
            sa.Column("id", sa.Integer(), primary_key=True, nullable=False),
            sa.Column("webhook_id", sa.String(), nullable=False),
            sa.Column("event", sa.String(), nullable=False),
            sa.Column("bot_id", sa.String(), nullable=True),
            sa.Column("recording_id", sa.String(), nullable=True),
            sa.Column("transcript_id", sa.String(), nullable=True),
            sa.Column("status_code", sa.String(), nullable=True),
            sa.Column("status_sub_code", sa.String(), nullable=True),
            sa.Column("payload", sa.Text(), nullable=False),
            sa.Column("processed_at", sa.DateTime(timezone=True), nullable=True),
            sa.Column("processing_error", sa.Text(), nullable=True),
            sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.text("NOW()"), nullable=True),
        )
        inspector = sa.inspect(bind)

    existing_indexes = {index["name"] for index in inspector.get_indexes("recall_webhook_events")}
    if "ix_recall_webhook_events_id" not in existing_indexes:
        op.create_index("ix_recall_webhook_events_id", "recall_webhook_events", ["id"], unique=False)
    if "ix_recall_webhook_events_webhook_id" not in existing_indexes:
        op.create_index("ix_recall_webhook_events_webhook_id", "recall_webhook_events", ["webhook_id"], unique=True)
    if "ix_recall_webhook_events_bot_id" not in existing_indexes:
        op.create_index("ix_recall_webhook_events_bot_id", "recall_webhook_events", ["bot_id"], unique=False)
    if "ix_recall_webhook_events_recording_id" not in existing_indexes:
        op.create_index("ix_recall_webhook_events_recording_id", "recall_webhook_events", ["recording_id"], unique=False)
    if "ix_recall_webhook_events_transcript_id" not in existing_indexes:
        op.create_index("ix_recall_webhook_events_transcript_id", "recall_webhook_events", ["transcript_id"], unique=False)


def downgrade() -> None:
    op.drop_index("ix_recall_webhook_events_transcript_id", table_name="recall_webhook_events")
    op.drop_index("ix_recall_webhook_events_recording_id", table_name="recall_webhook_events")
    op.drop_index("ix_recall_webhook_events_bot_id", table_name="recall_webhook_events")
    op.drop_index("ix_recall_webhook_events_webhook_id", table_name="recall_webhook_events")
    op.drop_index("ix_recall_webhook_events_id", table_name="recall_webhook_events")
    op.drop_table("recall_webhook_events")
