"""Add tier_id FK to vendor_subscriptions

Revision ID: k9f0a1b2c3d4
Revises: 2953ed10d22c
Create Date: 2025-12-26

Adds tier_id column to vendor_subscriptions table with FK to subscription_tiers.
Backfills tier_id based on existing tier (code) values.
"""

import sqlalchemy as sa

from alembic import op

# revision identifiers, used by Alembic.
revision = "k9f0a1b2c3d4"
down_revision = "2953ed10d22c"
branch_labels = None
depends_on = None


def upgrade() -> None:
    # Use batch mode for SQLite compatibility
    with op.batch_alter_table("vendor_subscriptions", schema=None) as batch_op:
        # Add tier_id column (nullable for backfill)
        batch_op.add_column(
            sa.Column("tier_id", sa.Integer(), nullable=True)
        )
        # Create index for tier_id
        batch_op.create_index(
            "ix_vendor_subscriptions_tier_id",
            ["tier_id"],
            unique=False,
        )
        # Add FK constraint
        batch_op.create_foreign_key(
            "fk_vendor_subscriptions_tier_id",
            "subscription_tiers",
            ["tier_id"],
            ["id"],
            ondelete="SET NULL",
        )

    # Backfill tier_id from tier code
    # This updates existing subscriptions to link to their tier
    op.execute(
        """
        UPDATE vendor_subscriptions
        SET tier_id = (
            SELECT id FROM subscription_tiers
            WHERE subscription_tiers.code = vendor_subscriptions.tier
        )
        WHERE EXISTS (
            SELECT 1 FROM subscription_tiers
            WHERE subscription_tiers.code = vendor_subscriptions.tier
        )
        """
    )


def downgrade() -> None:
    # In SQLite batch mode, we must explicitly drop the index before dropping
    # the column, otherwise batch mode will try to recreate the index on the
    # new table (which won't have the column).
    with op.batch_alter_table("vendor_subscriptions", schema=None) as batch_op:
        # First drop the index on tier_id
        batch_op.drop_index("ix_vendor_subscriptions_tier_id")
        # Then drop the column (FK is automatically removed with the column)
        batch_op.drop_column("tier_id")
