"""Add channel_pipeline_readiness cache for async readiness reports.

Revision ID: 0042_add_channel_pipeline_readiness_cache
Revises: 0041_add_master_product_image
Create Date: 2026-06-15 12:00:00.000000
"""

from __future__ import annotations

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

revision = "0042_add_channel_pipeline_readiness_cache"
down_revision = "0041_add_master_product_image"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.create_table(
        "channel_pipeline_readiness",
        sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True),
        sa.Column("channel_code", sa.String(32), nullable=False),
        sa.Column("scope_key", sa.String(255), nullable=False),
        sa.Column("only_assigned", sa.Boolean(), nullable=False, server_default=sa.text("true")),
        sa.Column("connection_id", sa.Integer(), nullable=True),
        sa.Column("magento_connection_id", sa.Integer(), nullable=True),
        sa.Column("shopify_connection_id", sa.Integer(), nullable=True),
        sa.Column("status", sa.String(32), nullable=False, server_default="missing"),
        sa.Column("report", postgresql.JSONB(astext_type=sa.Text()), nullable=True),
        sa.Column("last_error", sa.Text(), nullable=True),
        sa.Column("refresh_requested_at", sa.DateTime(timezone=True), nullable=True),
        sa.Column("refresh_started_at", sa.DateTime(timezone=True), nullable=True),
        sa.Column("computed_at", sa.DateTime(timezone=True), nullable=True),
        sa.Column("locked_at", sa.DateTime(timezone=True), nullable=True),
        sa.Column("locked_by", sa.String(128), nullable=True),
        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.UniqueConstraint("channel_code", "scope_key", name="uq_channel_pipeline_readiness_scope"),
    )
    op.create_index("ix_channel_pipeline_readiness_channel_code", "channel_pipeline_readiness", ["channel_code"])
    op.create_index("ix_channel_pipeline_readiness_status", "channel_pipeline_readiness", ["status"])
    op.create_index(
        "ix_channel_pipeline_readiness_refresh_requested_at",
        "channel_pipeline_readiness",
        ["refresh_requested_at"],
    )


def downgrade() -> None:
    op.drop_index("ix_channel_pipeline_readiness_refresh_requested_at", table_name="channel_pipeline_readiness")
    op.drop_index("ix_channel_pipeline_readiness_status", table_name="channel_pipeline_readiness")
    op.drop_index("ix_channel_pipeline_readiness_channel_code", table_name="channel_pipeline_readiness")
    op.drop_table("channel_pipeline_readiness")
