"""add_integration_sync_runs_table

Revision ID: k5f6g7h8i9j0
Revises: j4e5f6g7h8i9
Create Date: 2025-12-28 23:00: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 = "k5f6g7h8i9j0"
down_revision: str | Sequence[str] | None = "j4e5f6g7h8i9"
branch_labels: str | Sequence[str] | None = None
depends_on: str | Sequence[str] | None = None


def upgrade() -> None:
    """Create integration_sync_runs table."""
    op.create_table(
        "integration_sync_runs",
        sa.Column(
            "id",
            postgresql.UUID(as_uuid=True),
            primary_key=True,
            server_default=sa.text("gen_random_uuid()"),
        ),
        sa.Column(
            "integration_id",
            postgresql.UUID(as_uuid=True),
            sa.ForeignKey("noteflow.integrations.id", ondelete="CASCADE"),
            nullable=False,
        ),
        sa.Column("status", sa.Text(), nullable=False),
        sa.Column(
            "started_at",
            sa.DateTime(timezone=True),
            nullable=False,
            server_default=sa.text("now()"),
        ),
        sa.Column("ended_at", sa.DateTime(timezone=True), nullable=True),
        sa.Column("duration_ms", sa.Integer(), nullable=True),
        sa.Column("error_message", sa.Text(), nullable=True),
        sa.Column(
            "stats",
            postgresql.JSONB(),
            nullable=False,
            server_default=sa.text("'{}'::jsonb"),
        ),
        sa.CheckConstraint(
            "status IN ('running', 'success', 'error')",
            name="integration_sync_runs_status_chk",
        ),
        schema="noteflow",
    )

    op.create_index(
        "idx_integration_sync_runs_integration_id",
        "integration_sync_runs",
        ["integration_id", "started_at"],
        schema="noteflow",
    )


def downgrade() -> None:
    """Drop integration_sync_runs table."""
    op.drop_index(
        "idx_integration_sync_runs_integration_id",
        table_name="integration_sync_runs",
        schema="noteflow",
    )
    op.drop_table("integration_sync_runs", schema="noteflow")
