"""Pricing enhancements: OutputType→PricingTier link, per-line unit_price, transparent_bg, default tier

Revision ID: 016
Revises: 015
Create Date: 2026-03-02

"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa

revision: str = "016"
down_revision: Union[str, None] = "015"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # OutputType → PricingTier link
    op.add_column("output_types", sa.Column("pricing_tier_id", sa.Integer(), nullable=True))
    op.create_foreign_key(
        "fk_output_types_pricing_tier_id",
        "output_types",
        "pricing_tiers",
        ["pricing_tier_id"],
        ["id"],
        ondelete="SET NULL",
    )
    op.create_index("ix_output_types_pricing_tier_id", "output_types", ["pricing_tier_id"])

    # Transparent background option for Blender PNG renders
    op.add_column("output_types", sa.Column(
        "transparent_bg", sa.Boolean(), nullable=False, server_default="false",
    ))

    # Per-line price snapshot
    op.add_column("order_lines", sa.Column("unit_price", sa.Numeric(10, 2), nullable=True))

    # Seed global default tier (idempotent via ON CONFLICT)
    op.execute("""
        INSERT INTO pricing_tiers (category_key, quality_level, price_per_item, description, is_active, created_at, updated_at)
        VALUES ('default', 'Normal', 25.00, 'Global fallback price', true, NOW(), NOW())
        ON CONFLICT ON CONSTRAINT uq_pricing_tier DO NOTHING
    """)


def downgrade() -> None:
    op.drop_column("order_lines", "unit_price")
    op.drop_column("output_types", "transparent_bg")
    op.drop_index("ix_output_types_pricing_tier_id", table_name="output_types")
    op.drop_constraint("fk_output_types_pricing_tier_id", "output_types", type_="foreignkey")
    op.drop_column("output_types", "pricing_tier_id")
