"""Render templates — .blend file templates per category/output type

Revision ID: 018
Revises: 017
Create Date: 2026-03-02

"""
from typing import Sequence, Union
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import UUID

# revision identifiers, used by Alembic.
revision: str = "018"
down_revision: Union[str, None] = "017"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    op.create_table(
        "render_templates",
        sa.Column("id", UUID(as_uuid=True), primary_key=True, server_default=sa.text("gen_random_uuid()")),
        sa.Column("name", sa.String(300), nullable=False),
        sa.Column("category_key", sa.String(100), nullable=True),
        sa.Column("output_type_id", UUID(as_uuid=True), sa.ForeignKey("output_types.id", ondelete="SET NULL"), nullable=True),
        sa.Column("blend_file_path", sa.Text, nullable=False),
        sa.Column("original_filename", sa.String(500), nullable=False),
        sa.Column("target_collection", sa.String(200), server_default="Product", nullable=False),
        sa.Column("material_replace_enabled", sa.Boolean, server_default="false", nullable=False),
        sa.Column("is_active", sa.Boolean, server_default="true", nullable=False),
        sa.Column("created_at", sa.DateTime, server_default=sa.text("now()"), nullable=False),
        sa.Column("updated_at", sa.DateTime, server_default=sa.text("now()"), nullable=False),
    )

    # Unique constraint: one active template per (category_key, output_type_id) combo
    op.create_index(
        "ix_render_templates_active_unique",
        "render_templates",
        ["category_key", "output_type_id"],
        unique=True,
        postgresql_where=sa.text("is_active = true"),
    )

    # Seed material_library_path setting
    op.execute(
        "INSERT INTO system_settings (key, value, updated_at) "
        "VALUES ('material_library_path', '', now()) "
        "ON CONFLICT (key) DO NOTHING"
    )


def downgrade() -> None:
    op.drop_index("ix_render_templates_active_unique", table_name="render_templates")
    op.drop_table("render_templates")
    op.execute("DELETE FROM system_settings WHERE key = 'material_library_path'")
