"""desktop_configs: oem_id + unique (name, oem_id)

Revision ID: 010
Revises: 009
Create Date: 2026-05-21

"""

from typing import Sequence, Union

import sqlalchemy as sa
from alembic import op

revision: str = "010"
down_revision: Union[str, None] = "009"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def _drop_name_unique(conn) -> None:
    inspector = sa.inspect(conn)
    for uc in inspector.get_unique_constraints("desktop_configs"):
        cols = uc.get("column_names") or []
        if cols == ["name"]:
            op.drop_constraint(uc["name"], "desktop_configs", type_="unique")
            return

    for idx in inspector.get_indexes("desktop_configs"):
        if idx.get("column_names") == ["name"] and idx.get("unique"):
            op.drop_index(idx["name"], table_name="desktop_configs")
            return


def upgrade() -> None:
    conn = op.get_bind()
    inspector = sa.inspect(conn)
    columns = {c["name"] for c in inspector.get_columns("desktop_configs")}

    if "oem_id" not in columns:
        op.add_column(
            "desktop_configs",
            sa.Column("oem_id", sa.Integer(), nullable=False, server_default="1"),
        )

    unique_names = {uc["name"] for uc in inspector.get_unique_constraints("desktop_configs")}
    if "uq_desktop_configs_name_oem_id" not in unique_names:
        _drop_name_unique(conn)
        op.create_unique_constraint(
            "uq_desktop_configs_name_oem_id",
            "desktop_configs",
            ["name", "oem_id"],
        )

    inspector = sa.inspect(conn)
    index_names = {idx["name"] for idx in inspector.get_indexes("desktop_configs")}
    if "ix_desktop_configs_name" not in index_names:
        op.create_index("ix_desktop_configs_name", "desktop_configs", ["name"], unique=False)
    if "ix_desktop_configs_oem_id" not in index_names:
        op.create_index("ix_desktop_configs_oem_id", "desktop_configs", ["oem_id"], unique=False)


def downgrade() -> None:
    op.drop_index("ix_desktop_configs_oem_id", table_name="desktop_configs")
    op.drop_index("ix_desktop_configs_name", table_name="desktop_configs")
    op.drop_constraint("uq_desktop_configs_name_oem_id", "desktop_configs", type_="unique")
    op.create_unique_constraint("name", "desktop_configs", ["name"])
    op.drop_column("desktop_configs", "oem_id")
