"""Add webhook api key

Revision ID: 62bd5a3dccde
Revises: 2d6eadcf4976
Create Date: 2025-10-29 23:39:52.008342

"""

from collections.abc import Sequence

import sqlalchemy as sa
from sqlalchemy.dialects import postgresql

from alembic import op

# revision identifiers, used by Alembic.
revision: str = "62bd5a3dccde"
down_revision: str | None = "2d6eadcf4976"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def upgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_table(
        "webhook_api_key",
        sa.Column(
            "created_at",
            sa.TIMESTAMP(timezone=True),
            server_default=sa.text("now()"),
            nullable=False,
        ),
        sa.Column(
            "updated_at",
            sa.TIMESTAMP(timezone=True),
            server_default=sa.text("now()"),
            nullable=False,
        ),
        sa.Column("surrogate_id", sa.Integer(), nullable=False),
        sa.Column("owner_id", postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column("id", postgresql.UUID(as_uuid=True), nullable=False),
        sa.Column("webhook_id", sa.String(), nullable=True),
        sa.Column("hashed", sa.String(length=128), nullable=False),
        sa.Column("salt", sa.String(length=64), nullable=False),
        sa.Column("preview", sa.String(length=16), nullable=False),
        sa.Column("last_used_at", sa.TIMESTAMP(timezone=True), nullable=True),
        sa.Column("revoked_at", sa.TIMESTAMP(timezone=True), nullable=True),
        sa.Column("revoked_by", sa.UUID(), nullable=True),
        sa.ForeignKeyConstraint(
            ["webhook_id"],
            ["webhook.id"],
            ondelete="CASCADE",
            name="webhook_api_key_webhook_id_fkey",
        ),
        sa.PrimaryKeyConstraint("surrogate_id", name="webhook_api_key_pkey"),
        sa.UniqueConstraint("webhook_id", name="webhook_api_key_webhook_id_key"),
    )
    op.create_index(
        op.f("ix_webhook_api_key_id"), "webhook_api_key", ["id"], unique=True
    )
    op.add_column(
        "webhook",
        sa.Column(
            "allowlisted_cidrs",
            postgresql.JSONB(astext_type=sa.Text()),
            server_default=sa.text("'[]'::jsonb"),
            nullable=False,
        ),
    )
    # ### end Alembic commands ###


def downgrade() -> None:
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column("webhook", "allowlisted_cidrs")
    op.drop_index(op.f("ix_webhook_api_key_id"), table_name="webhook_api_key")
    op.drop_table("webhook_api_key")
    # ### end Alembic commands ###
