"""backfill attribute_def options_json

Revision ID: 0005_backfill_attribute_def_options_json
Revises: 0004_attribute_def_options_json
Create Date: 2026-01-24 00:55:00.000000
"""

from alembic import op


revision = "0005_backfill_attribute_def_options_json"
down_revision = "0004_attribute_def_options_json"
branch_labels = None
depends_on = None


def upgrade() -> None:
    op.execute(
        """
        UPDATE attribute_def d
        SET options_json = sub.options
        FROM (
            SELECT attribute_code, jsonb_agg(option_value ORDER BY option_value) AS options
            FROM attribute_option
            GROUP BY attribute_code
        ) AS sub
        WHERE d.attribute_code = sub.attribute_code
          AND (d.options_json IS NULL OR jsonb_array_length(d.options_json) = 0);
        """
    )


def downgrade() -> None:
    op.execute(
        """
        UPDATE attribute_def
        SET options_json = NULL;
        """
    )
