"""config_options per-product

Revision ID: 012
Revises: 011
Create Date: 2026-05-16 12:00:00.000000

- config_option_groups 加 global / product_id：global=1 时 product_id=NULL，
  global=0 时 product_id 指向 products.id（产品专属组，删产品时级联删）。
- config_options 删 key 字段：name 直接存 `os|系统镜像` 这种复合字符串，
  含 `|` 时前面是提交键、后面是展示；不含 `|` 时是纯展示字段（不提交）。
"""
from typing import Sequence, Union

import sqlalchemy as sa
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:
    op.add_column(
        "config_option_groups",
        sa.Column(
            "is_global",
            sa.Boolean(),
            nullable=False,
            server_default="1",
            comment="1=公共组(可挂多产品)，0=产品专属",
        ),
    )
    op.add_column(
        "config_option_groups",
        sa.Column(
            "product_id",
            sa.Integer(),
            nullable=True,
            comment="专属组归属产品；global=1 时为 NULL",
        ),
    )
    op.create_foreign_key(
        "fk_config_option_groups_product_id",
        "config_option_groups",
        "products",
        ["product_id"],
        ["id"],
        ondelete="CASCADE",
    )
    op.create_index(
        "ix_config_option_groups_product_id", "config_option_groups", ["product_id"]
    )

    op.drop_column("config_options", "key")


def downgrade() -> None:
    op.add_column(
        "config_options",
        sa.Column("key", sa.String(length=64), nullable=False, server_default=""),
    )

    op.drop_index("ix_config_option_groups_product_id", table_name="config_option_groups")
    op.drop_constraint(
        "fk_config_option_groups_product_id", "config_option_groups", type_="foreignkey"
    )
    op.drop_column("config_option_groups", "product_id")
    op.drop_column("config_option_groups", "is_global")
