"""M2M table for render templates ↔ output types.

Allows one render template to be linked to multiple output types.

Revision ID: 047
Revises: 046
"""
from alembic import op
import sqlalchemy as sa
from sqlalchemy.dialects.postgresql import UUID

revision = "047"
down_revision = "046"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.create_table(
        "render_template_output_types",
        sa.Column("template_id", UUID(as_uuid=True), sa.ForeignKey("render_templates.id", ondelete="CASCADE"), nullable=False),
        sa.Column("output_type_id", UUID(as_uuid=True), sa.ForeignKey("output_types.id", ondelete="CASCADE"), nullable=False),
        sa.PrimaryKeyConstraint("template_id", "output_type_id"),
    )

    # Backfill from existing render_templates.output_type_id
    op.execute("""
        INSERT INTO render_template_output_types (template_id, output_type_id)
        SELECT id, output_type_id FROM render_templates
        WHERE output_type_id IS NOT NULL
        ON CONFLICT DO NOTHING
    """)


def downgrade() -> None:
    op.drop_table("render_template_output_types")
