"""Backfill products and order_lines from order_items

Revision ID: 012
Revises: 011
Create Date: 2026-03-02

"""
from typing import Sequence, Union
from alembic import op

revision: str = "012"
down_revision: Union[str, None] = "011"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
    # 1. Seed default output type
    op.execute(
        """
        INSERT INTO output_types (id, name, renderer, output_format, sort_order)
        VALUES (gen_random_uuid(), '3D Thumbnail', 'threejs', 'png', 0)
        ON CONFLICT (name) DO NOTHING
        """
    )

    # 2. Create products from distinct pim_id in order_items
    #    For each distinct pim_id, take fields from the most recently updated row
    op.execute(
        """
        INSERT INTO products (
            pim_id, name, category_key, ebene1, ebene2, baureihe,
            produkt_baureihe, lagertyp, name_cad_modell,
            components, cad_part_materials, cad_file_id, source_excel
        )
        SELECT DISTINCT ON (oi.pim_id)
            oi.pim_id,
            oi.gewaehltes_produkt          AS name,
            t.category_key,
            oi.ebene1,
            oi.ebene2,
            oi.baureihe,
            oi.produkt_baureihe,
            oi.lagertyp,
            oi.name_cad_modell,
            oi.components,
            COALESCE(oi.cad_part_materials, '[]'::jsonb) AS cad_part_materials,
            oi.cad_file_id,
            o.source_excel
        FROM order_items oi
        JOIN orders o ON o.id = oi.order_id
        LEFT JOIN templates t ON t.id = o.template_id
        WHERE oi.pim_id IS NOT NULL
          AND oi.pim_id <> ''
        ORDER BY oi.pim_id, oi.updated_at DESC
        ON CONFLICT (pim_id) DO NOTHING
        """
    )

    # 3. Create order_lines from order_items where pim_id IS NOT NULL
    #    3a. Rows with medias_rendering = true → link to '3D Thumbnail' output type
    op.execute(
        """
        INSERT INTO order_lines (
            order_id, product_id, output_type_id,
            gewuenschte_bildnummer, item_status, render_status,
            ai_validation_status, ai_validation_result, notes
        )
        SELECT
            oi.order_id,
            p.id                  AS product_id,
            ot.id                 AS output_type_id,
            oi.gewuenschte_bildnummer,
            oi.item_status::TEXT,
            CASE
                WHEN oi.cad_file_id IS NOT NULL THEN 'pending'
                ELSE 'pending'
            END                   AS render_status,
            oi.ai_validation_status::TEXT,
            oi.ai_validation_result,
            oi.notes
        FROM order_items oi
        JOIN products p ON p.pim_id = oi.pim_id
        JOIN output_types ot ON ot.name = '3D Thumbnail'
        WHERE oi.pim_id IS NOT NULL
          AND oi.pim_id <> ''
          AND oi.medias_rendering = TRUE
        ON CONFLICT DO NOTHING
        """
    )

    # 3b. Rows with medias_rendering = false → tracking only (no output_type_id)
    op.execute(
        """
        INSERT INTO order_lines (
            order_id, product_id, output_type_id,
            gewuenschte_bildnummer, item_status, render_status,
            ai_validation_status, ai_validation_result, notes
        )
        SELECT
            oi.order_id,
            p.id                  AS product_id,
            NULL                  AS output_type_id,
            oi.gewuenschte_bildnummer,
            oi.item_status::TEXT,
            'pending'             AS render_status,
            oi.ai_validation_status::TEXT,
            oi.ai_validation_result,
            oi.notes
        FROM order_items oi
        JOIN products p ON p.pim_id = oi.pim_id
        WHERE oi.pim_id IS NOT NULL
          AND oi.pim_id <> ''
          AND (oi.medias_rendering IS NULL OR oi.medias_rendering = FALSE)
        ON CONFLICT DO NOTHING
        """
    )


def downgrade() -> None:
    op.execute("DELETE FROM order_lines")
    op.execute("DELETE FROM products")
    op.execute("DELETE FROM output_types WHERE name = '3D Thumbnail'")
