"""add platform_id to store_domains

Revision ID: z_store_domain_platform_id
Revises: core_001
Create Date: 2026-02-08
"""
from alembic import op
import sqlalchemy as sa

revision = "z_store_domain_platform_id"
down_revision = "core_001"
branch_labels = None
depends_on = None


def upgrade() -> None:
    # Add platform_id column
    op.add_column(
        "store_domains",
        sa.Column(
            "platform_id",
            sa.Integer(),
            sa.ForeignKey("platforms.id", ondelete="SET NULL"),
            nullable=True,
            comment="Platform this domain is associated with (for platform context resolution)",
        ),
    )
    op.create_index("idx_store_domain_platform", "store_domains", ["platform_id"])

    # Backfill: set platform_id from the store's primary store_platform
    op.execute(
        """
        UPDATE store_domains sd
        SET platform_id = (
            SELECT sp.platform_id
            FROM store_platforms sp
            WHERE sp.store_id = sd.store_id
              AND sp.is_primary = true
            LIMIT 1
        )
        WHERE sd.platform_id IS NULL
        """
    )


def downgrade() -> None:
    op.drop_index("idx_store_domain_platform", table_name="store_domains")
    op.drop_column("store_domains", "platform_id")
