"""snapshot writes to postgres (products/nav/listings/reports)

Revision ID: 20251107_090500_snapshot_to_db
Revises: 20251106_152905_calendar_config
Create Date: 2025-11-07T09:05:00.000000
"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = "20251107_090500_snapshot_to_db"
down_revision = "20251106_152905_calendar_config"
branch_labels = None
depends_on = None


def upgrade() -> None:
    # products (if not already present in your DB — keep idempotent with if_exists checks in env if needed)
    if not op.get_bind().dialect.has_table(op.get_bind(), "products"):
        op.create_table(
            "products",
            sa.Column("id", sa.Integer(), primary_key=True),
            sa.Column("slug", sa.String(length=255), nullable=False, unique=True),
            sa.Column("title", sa.String(length=512), nullable=True),
            sa.Column("image", sa.Text(), nullable=True),
            sa.Column("description_short", sa.Text(), nullable=True),
            sa.Column("description_html", sa.Text(), nullable=True),
            sa.Column("suma_href", sa.Text(), nullable=True),
            sa.Column("brand", sa.String(length=255), nullable=True),
            sa.Column("rrp", sa.Numeric(12, 2), nullable=True),
            sa.Column("rrp_currency", sa.String(length=16), nullable=True),
            sa.Column("rrp_raw", sa.String(length=128), nullable=True),
            sa.Column("price_per_unit", sa.Numeric(12, 4), nullable=True),
            sa.Column("price_per_unit_currency", sa.String(length=16), nullable=True),
            sa.Column("price_per_unit_raw", sa.String(length=128), nullable=True),
            sa.Column("special_price", sa.Numeric(12, 2), nullable=True),
            sa.Column("special_price_currency", sa.String(length=16), nullable=True),
            sa.Column("special_price_raw", sa.String(length=128), nullable=True),
            sa.Column("case_size_count", sa.Integer(), nullable=True),
            sa.Column("case_size_item_qty", sa.Numeric(12, 3), nullable=True),
            sa.Column("case_size_item_unit", sa.String(length=32), nullable=True),
            sa.Column("case_size_raw", sa.String(length=128), nullable=True),
            sa.Column("created_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
            sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
            sa.Column("deleted_at", sa.DateTime(timezone=True), nullable=True),
        )
        op.create_index("ix_products_slug", "products", ["slug"], unique=False)

    # product_sections
    if not op.get_bind().dialect.has_table(op.get_bind(), "product_sections"):
        op.create_table(
            "product_sections",
            sa.Column("id", sa.Integer(), primary_key=True),
            sa.Column("product_id", sa.Integer(), sa.ForeignKey("products.id", ondelete="CASCADE"), nullable=False),
            sa.Column("title", sa.String(length=255), nullable=False),
            sa.Column("html", sa.Text(), nullable=False),
        )
        op.create_index("ix_product_sections_product_id", "product_sections", ["product_id"], unique=False)
        op.create_unique_constraint("uq_product_sections_product_title", "product_sections", ["product_id", "title"])

    # product_images (add kind + adjust unique)
    if not op.get_bind().dialect.has_table(op.get_bind(), "product_images"):
        op.create_table(
            "product_images",
            sa.Column("id", sa.Integer(), primary_key=True),
            sa.Column("product_id", sa.Integer(), sa.ForeignKey("products.id", ondelete="CASCADE"), nullable=False),
            sa.Column("url", sa.Text(), nullable=False),
            sa.Column("position", sa.Integer(), nullable=False, server_default="0"),
            sa.Column("kind", sa.String(length=16), nullable=False, server_default="gallery"),
            sa.CheckConstraint("position >= 0", name="ck_product_images_position_nonneg"),
        )
        op.create_index("ix_product_images_product_id", "product_images", ["product_id"], unique=False)
        op.create_index("ix_product_images_position", "product_images", ["position"], unique=False)
        op.create_unique_constraint("uq_product_images_product_url_kind", "product_images", ["product_id", "url", "kind"])
    else:
        # alter existing table to add `kind` and update unique
        with op.batch_alter_table("product_images") as batch_op:
            if not op.get_bind().dialect.has_column(op.get_bind(), "product_images", "kind"):
                batch_op.add_column(sa.Column("kind", sa.String(length=16), nullable=False, server_default="gallery"))
            try:
                batch_op.drop_constraint("uq_product_images_product_url", type_="unique")
            except Exception:
                pass
            batch_op.create_unique_constraint("uq_product_images_product_url_kind", ["product_id", "url", "kind"])

    # nav_tops / nav_subs
    op.create_table(
        "nav_tops",
        sa.Column("id", sa.Integer(), primary_key=True),
        sa.Column("label", sa.String(length=255), nullable=False),
        sa.Column("slug", sa.String(length=255), nullable=False),
        sa.Column("created_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
        sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
    )
    op.create_index("ix_nav_tops_slug", "nav_tops", ["slug"], unique=False)
    op.create_unique_constraint("uq_nav_tops_label_slug", "nav_tops", ["label", "slug"])

    op.create_table(
        "nav_subs",
        sa.Column("id", sa.Integer(), primary_key=True),
        sa.Column("top_id", sa.Integer(), sa.ForeignKey("nav_tops.id", ondelete="CASCADE"), nullable=False),
        sa.Column("label", sa.String(length=255), nullable=True),
        sa.Column("slug", sa.String(length=255), nullable=False),
        sa.Column("href", sa.Text(), nullable=True),
    )
    op.create_index("ix_nav_subs_top_id", "nav_subs", ["top_id"], unique=False)
    op.create_index("ix_nav_subs_slug", "nav_subs", ["slug"], unique=False)
    op.create_unique_constraint("uq_nav_subs_top_slug", "nav_subs", ["top_id", "slug"])

    # listings & listing_items
    op.create_table(
        "listings",
        sa.Column("id", sa.Integer(), primary_key=True),
        sa.Column("top_slug", sa.String(length=255), nullable=False),
        sa.Column("sub_slug", sa.String(length=255), nullable=True),
        sa.Column("total_pages", sa.Integer(), nullable=True),
        sa.Column("created_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
    )
    op.create_index("ix_listings_top_slug", "listings", ["top_slug"], unique=False)
    op.create_index("ix_listings_sub_slug", "listings", ["sub_slug"], unique=False)
    op.create_unique_constraint("uq_listings_top_sub", "listings", ["top_slug", "sub_slug"])

    op.create_table(
        "listing_items",
        sa.Column("id", sa.Integer(), primary_key=True),
        sa.Column("listing_id", sa.Integer(), sa.ForeignKey("listings.id", ondelete="CASCADE"), nullable=False),
        sa.Column("slug", sa.String(length=255), nullable=False),
    )
    op.create_index("ix_listing_items_listing_id", "listing_items", ["listing_id"], unique=False)
    op.create_index("ix_listing_items_slug", "listing_items", ["slug"], unique=False)
    op.create_unique_constraint("uq_listing_items_listing_slug", "listing_items", ["listing_id", "slug"])

    # reports: link_errors, link_externals, subcategory_redirects, product_logs
    op.create_table(
        "link_errors",
        sa.Column("id", sa.Integer(), primary_key=True),
        sa.Column("product_slug", sa.String(length=255), nullable=True),
        sa.Column("href", sa.Text(), nullable=True),
        sa.Column("text", sa.Text(), nullable=True),
        sa.Column("top", sa.String(length=255), nullable=True),
        sa.Column("sub", sa.String(length=255), nullable=True),
        sa.Column("target_slug", sa.String(length=255), nullable=True),
        sa.Column("type", sa.String(length=255), nullable=True),
        sa.Column("created_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
    )
    op.create_index("ix_link_errors_product_slug", "link_errors", ["product_slug"], unique=False)

    op.create_table(
        "link_externals",
        sa.Column("id", sa.Integer(), primary_key=True),
        sa.Column("product_slug", sa.String(length=255), nullable=True),
        sa.Column("href", sa.Text(), nullable=True),
        sa.Column("text", sa.Text(), nullable=True),
        sa.Column("host", sa.String(length=255), nullable=True),
        sa.Column("created_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
    )
    op.create_index("ix_link_externals_product_slug", "link_externals", ["product_slug"], unique=False)

    op.create_table(
        "subcategory_redirects",
        sa.Column("id", sa.Integer(), primary_key=True),
        sa.Column("old_path", sa.String(length=512), nullable=False),
        sa.Column("new_path", sa.String(length=512), nullable=False),
        sa.Column("created_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
    )
    op.create_index("ix_subcategory_redirects_old_path", "subcategory_redirects", ["old_path"], unique=False)
    op.create_unique_constraint("uq_subcategory_redirects_old_new", "subcategory_redirects", ["old_path", "new_path"])

    op.create_table(
        "product_logs",
        sa.Column("id", sa.Integer(), primary_key=True),
        sa.Column("slug", sa.String(length=255), nullable=True),
        sa.Column("href_tried", sa.Text(), nullable=True),
        sa.Column("ok", sa.Boolean(), nullable=False, server_default=sa.false()),
        sa.Column("error_type", sa.String(length=255), nullable=True),
        sa.Column("error_message", sa.Text(), nullable=True),
        sa.Column("http_status", sa.Integer(), nullable=True),
        sa.Column("final_url", sa.Text(), nullable=True),
        sa.Column("transport_error", sa.Boolean(), nullable=True),
        sa.Column("title", sa.String(length=512), nullable=True),
        sa.Column("has_description_html", sa.Boolean(), nullable=True),
        sa.Column("has_description_short", sa.Boolean(), nullable=True),
        sa.Column("sections_count", sa.Integer(), nullable=True),
        sa.Column("images_count", sa.Integer(), nullable=True),
        sa.Column("embedded_images_count", sa.Integer(), nullable=True),
        sa.Column("all_images_count", sa.Integer(), nullable=True),
        sa.Column("created_at", sa.DateTime(timezone=True), nullable=False, server_default=sa.func.now()),
    )
    op.create_index("ix_product_logs_slug", "product_logs", ["slug"], unique=False)


def downgrade() -> None:
    op.drop_index("ix_product_logs_slug", table_name="product_logs")
    op.drop_table("product_logs")

    op.drop_constraint("uq_subcategory_redirects_old_new", "subcategory_redirects", type_="unique")
    op.drop_index("ix_subcategory_redirects_old_path", table_name="subcategory_redirects")
    op.drop_table("subcategory_redirects")

    op.drop_index("ix_link_externals_product_slug", table_name="link_externals")
    op.drop_table("link_externals")

    op.drop_index("ix_link_errors_product_slug", table_name="link_errors")
    op.drop_table("link_errors")

    op.drop_index("ix_listing_items_slug", table_name="listing_items")
    op.drop_index("ix_listing_items_listing_id", table_name="listing_items")
    op.drop_table("listing_items")

    op.drop_constraint("uq_listings_top_sub", "listings", type_="unique")
    op.drop_index("ix_listings_sub_slug", table_name="listings")
    op.drop_index("ix_listings_top_slug", table_name="listings")
    op.drop_table("listings")

    op.drop_constraint("uq_nav_subs_top_slug", "nav_subs", type_="unique")
    op.drop_index("ix_nav_subs_slug", table_name="nav_subs")
    op.drop_index("ix_nav_subs_top_id", table_name="nav_subs")
    op.drop_table("nav_subs")

    op.drop_constraint("uq_nav_tops_label_slug", "nav_tops", type_="unique")
    op.drop_index("ix_nav_tops_slug", table_name="nav_tops")
    op.drop_table("nav_tops")

    with op.batch_alter_table("product_images") as batch_op:
        try:
            batch_op.drop_constraint("uq_product_images_product_url_kind", type_="unique")
        except Exception:
            pass
        # Do not drop 'kind' column automatically since existing code may rely on it.
        # If needed, uncomment:
        # batch_op.drop_column("kind")
    op.drop_index("ix_product_images_position", table_name="product_images")
    op.drop_index("ix_product_images_product_id", table_name="product_images")
    op.drop_table("product_images")

    op.drop_constraint("uq_product_sections_product_title", "product_sections", type_="unique")
    op.drop_index("ix_product_sections_product_id", table_name="product_sections")
    op.drop_table("product_sections")

    op.drop_index("ix_products_slug", table_name="products")
    op.drop_table("products")
