"""Add payload JSONB column to github_webhook_events table.

Stores the full webhook payload for debugging and replay.

Revision ID: 0006
Revises: 0005
"""

from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op

revision: str = "0006"
down_revision: Union[str, None] = "0005"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    conn = op.get_bind()
    result = conn.execute(sa.text(
        "SELECT column_name FROM information_schema.columns "
        "WHERE table_name = 'github_webhook_events' AND column_name = 'payload'"
    ))
    columns = [row[0] for row in result]
    if "payload" not in columns:
        op.add_column(
            "github_webhook_events",
            sa.Column("payload", sa.JSON(), nullable=True),
        )


def downgrade() -> None:
    with op.batch_alter_table("github_webhook_events") as batch_op:
        batch_op.drop_column("payload")
