"""Add magento_attribute_cache and magento_attribute_option_cache.

Revision ID: 0016_add_magento_attribute_cache
Revises: 0015_add_product_version_status_backfill
Create Date: 2026-03-04

"""

from alembic import op
import sqlalchemy as sa


revision = "0016_add_magento_attribute_cache"
down_revision = "0015_add_product_version_status_backfill"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.create_table(
        "magento_attribute_cache",
        sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True),
        sa.Column("connection_id", sa.Integer(), sa.ForeignKey("magento_connections.id"), nullable=False),
        sa.Column("attribute_code", sa.Text(), nullable=False),
        sa.Column("attribute_id", sa.Integer(), nullable=False),
        sa.Column("frontend_label", sa.Text(), nullable=True),
        sa.Column("frontend_input", sa.Text(), nullable=True),
        sa.Column("backend_type", sa.Text(), nullable=True),
        sa.Column("is_user_defined", sa.Boolean(), nullable=True),
        sa.Column("fetched_at", sa.DateTime(timezone=True), nullable=False),
        sa.UniqueConstraint("connection_id", "attribute_code", name="uq_magento_attribute_cache_conn_code"),
    )
    op.create_index("ix_magento_attribute_cache_connection_id_fetched_at", "magento_attribute_cache", ["connection_id", "fetched_at"])
    op.create_index("ix_magento_attribute_cache_connection_id_attribute_code", "magento_attribute_cache", ["connection_id", "attribute_code"])

    op.create_table(
        "magento_attribute_option_cache",
        sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True),
        sa.Column("connection_id", sa.Integer(), sa.ForeignKey("magento_connections.id"), nullable=False),
        sa.Column("attribute_code", sa.Text(), nullable=False),
        sa.Column("option_label", sa.Text(), nullable=False),
        sa.Column("option_label_norm", sa.Text(), nullable=False),
        sa.Column("value_index", sa.Integer(), nullable=False),
        sa.Column("fetched_at", sa.DateTime(timezone=True), nullable=False),
        sa.UniqueConstraint("connection_id", "attribute_code", "option_label_norm", name="uq_magento_attribute_option_cache_conn_code_norm"),
    )
    op.create_index("ix_magento_attr_option_cache_connection_id_fetched_at", "magento_attribute_option_cache", ["connection_id", "fetched_at"])
    op.create_index("ix_magento_attr_option_cache_connection_id_attribute_code", "magento_attribute_option_cache", ["connection_id", "attribute_code"])


def downgrade() -> None:
    op.drop_table("magento_attribute_option_cache")
    op.drop_table("magento_attribute_cache")
