"""Add surrogate key and product_id FK to product_likes"""

from alembic import op
import sqlalchemy as sa

# Revision identifiers
revision = '20251107_add_product_id_to_likes'
down_revision = '0d767ad92dd7'
branch_labels = None
depends_on = None


def upgrade() -> None:
    # Add surrogate primary key and product_id foreign key column
    op.add_column("product_likes", sa.Column("id", sa.Integer(), primary_key=True, autoincrement=True))
    op.add_column("product_likes", sa.Column("product_id", sa.Integer(), nullable=True))

    # Create temporary FK without constraint for backfill
    op.execute("""
        UPDATE product_likes
        SET product_id = (
            SELECT id FROM products WHERE products.slug = product_likes.product_slug
        )
    """)

    # Add real FK constraint
    op.create_foreign_key(
        "fk_product_likes_product_id_products",
        source_table="product_likes",
        referent_table="products",
        local_cols=["product_id"],
        remote_cols=["id"],
        ondelete="CASCADE"
    )

    # Make product_id non-nullable now that it’s backfilled
    op.alter_column("product_likes", "product_id", nullable=False)

    # Add index for efficient lookup
    op.create_index(
        "ix_product_likes_user_product",
        "product_likes",
        ["user_id", "product_id"],
        unique=True
    )


def downgrade() -> None:
    op.drop_index("ix_product_likes_user_product", table_name="product_likes")
    op.drop_constraint("fk_product_likes_product_id_products", "product_likes", type_="foreignkey")
    op.drop_column("product_likes", "product_id")
    op.drop_column("product_likes", "id")
