"""Add gewuenschte_bildnummer and medias_rendering to products

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

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

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


def upgrade() -> None:
    op.add_column("products", sa.Column("gewuenschte_bildnummer", sa.String(500), nullable=True))
    op.add_column("products", sa.Column("medias_rendering", sa.Boolean(), nullable=True))

    # Backfill from order_items where available
    op.execute(
        """
        UPDATE products p
        SET gewuenschte_bildnummer = sub.gewuenschte_bildnummer,
            medias_rendering = sub.medias_rendering
        FROM (
            SELECT DISTINCT ON (oi.pim_id)
                oi.pim_id,
                oi.gewuenschte_bildnummer,
                oi.medias_rendering
            FROM order_items oi
            WHERE oi.pim_id IS NOT NULL AND oi.pim_id <> ''
            ORDER BY oi.pim_id, oi.updated_at DESC
        ) sub
        WHERE p.pim_id = sub.pim_id
        """
    )


def downgrade() -> None:
    op.drop_column("products", "medias_rendering")
    op.drop_column("products", "gewuenschte_bildnummer")
