"""add_webhook_tables

Revision ID: i3d4e5f6g7h8
Revises: h2c3d4e5f6g7
Create Date: 2025-12-25 12:30:00.000000

"""

from collections.abc import Sequence

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

# revision identifiers, used by Alembic.
revision: str = "i3d4e5f6g7h8"
down_revision: str | Sequence[str] | None = "l6m7n8o9p0q1"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def upgrade() -> None:
    """Create webhook_configs and webhook_deliveries tables."""
    # webhook_configs table
    op.create_table(
        "webhook_configs",
        sa.Column(
            "id",
            postgresql.UUID(as_uuid=True),
            primary_key=True,
            server_default=sa.text("gen_random_uuid()"),
        ),
        sa.Column(
            "workspace_id",
            postgresql.UUID(as_uuid=True),
            sa.ForeignKey("noteflow.workspaces.id", ondelete="CASCADE"),
            nullable=False,
        ),
        sa.Column("name", sa.String(255), nullable=False, server_default="'Webhook'"),
        sa.Column("url", sa.Text(), nullable=False),
        sa.Column(
            "events",
            postgresql.ARRAY(sa.Text()),
            nullable=False,
            server_default="{}",
        ),
        sa.Column("secret", sa.Text(), nullable=True),
        sa.Column("enabled", sa.Boolean(), nullable=False, server_default="true"),
        sa.Column("timeout_ms", sa.Integer(), nullable=False, server_default="10000"),
        sa.Column("max_retries", sa.Integer(), nullable=False, server_default="3"),
        sa.Column(
            "created_at",
            sa.DateTime(timezone=True),
            nullable=False,
            server_default=sa.text("now()"),
        ),
        sa.Column(
            "updated_at",
            sa.DateTime(timezone=True),
            nullable=False,
            server_default=sa.text("now()"),
        ),
        sa.CheckConstraint("url ~ '^https?://'", name="chk_webhook_url_format"),
        schema="noteflow",
    )

    op.create_index(
        "idx_webhook_configs_workspace_id",
        "webhook_configs",
        ["workspace_id"],
        schema="noteflow",
    )

    # webhook_deliveries table
    op.create_table(
        "webhook_deliveries",
        sa.Column(
            "id",
            postgresql.UUID(as_uuid=True),
            primary_key=True,
            server_default=sa.text("gen_random_uuid()"),
        ),
        sa.Column(
            "webhook_id",
            postgresql.UUID(as_uuid=True),
            sa.ForeignKey("noteflow.webhook_configs.id", ondelete="CASCADE"),
            nullable=False,
        ),
        sa.Column("event_type", sa.Text(), nullable=False),
        sa.Column(
            "payload",
            postgresql.JSONB(),
            nullable=False,
            server_default=sa.text("'{}'::jsonb"),
        ),
        sa.Column("status_code", sa.Integer(), nullable=True),
        sa.Column("response_body", sa.Text(), nullable=True),
        sa.Column("error_message", sa.Text(), nullable=True),
        sa.Column("attempt_count", sa.Integer(), nullable=False, server_default="1"),
        sa.Column("duration_ms", sa.Integer(), nullable=True),
        sa.Column(
            "delivered_at",
            sa.DateTime(timezone=True),
            nullable=False,
            server_default=sa.text("now()"),
        ),
        schema="noteflow",
    )

    op.create_index(
        "idx_webhook_deliveries_webhook_id",
        "webhook_deliveries",
        ["webhook_id", "delivered_at"],
        schema="noteflow",
    )

    op.create_index(
        "idx_webhook_deliveries_event_type",
        "webhook_deliveries",
        ["event_type", "delivered_at"],
        schema="noteflow",
    )

    # Create updated_at trigger for webhook_configs
    op.execute(
        """
        CREATE TRIGGER trg_webhook_configs_updated_at
        BEFORE UPDATE ON noteflow.webhook_configs
        FOR EACH ROW EXECUTE FUNCTION noteflow.set_updated_at();
        """
    )


def downgrade() -> None:
    """Drop webhook tables."""
    # Drop trigger first
    op.execute(
        "DROP TRIGGER IF EXISTS trg_webhook_configs_updated_at ON noteflow.webhook_configs;"
    )

    op.drop_index(
        "idx_webhook_deliveries_event_type",
        table_name="webhook_deliveries",
        schema="noteflow",
    )
    op.drop_index(
        "idx_webhook_deliveries_webhook_id",
        table_name="webhook_deliveries",
        schema="noteflow",
    )
    op.drop_table("webhook_deliveries", schema="noteflow")

    op.drop_index(
        "idx_webhook_configs_workspace_id",
        table_name="webhook_configs",
        schema="noteflow",
    )
    op.drop_table("webhook_configs", schema="noteflow")
