import pytest

from dashboard_layout_schema import (
    ALLOWED_WIDGET_IDS,
    DashboardLayoutPayload,
    coalesce_effective_layout,
    default_layout_dict,
)
from widget_catalog import DEFAULT_PRODUCT_DASHBOARD_WIDGET_IDS


def test_default_has_all_allowed_ids():
    d = default_layout_dict()
    got = {w["id"] for w in d["widgets"]}
    assert got == ALLOWED_WIDGET_IDS
    assert {w["id"] for w in d["widgets"] if w["enabled"]} == DEFAULT_PRODUCT_DASHBOARD_WIDGET_IDS


def test_payload_rejects_duplicate_ids():
    with pytest.raises(Exception):
        DashboardLayoutPayload.model_validate(
            {
                "version": 1,
                "widgets": [
                    {"id": "welcome", "enabled": True},
                    {"id": "welcome", "enabled": False},
                ],
            }
        )


def test_payload_requires_one_enabled():
    with pytest.raises(Exception):
        DashboardLayoutPayload.model_validate(
            {
                "version": 1,
                "widgets": [{"id": "dashboard_greeting", "enabled": False}],
            }
        )


def test_coalesce_none():
    custom, eff = coalesce_effective_layout(None)
    assert custom is False
    assert eff == default_layout_dict()


def test_coalesce_valid_raw():
    raw = {
        "version": 1,
        "widgets": [
            {"id": "welcome", "enabled": True},
            {"id": "kpi_board", "enabled": True},
        ],
    }
    custom, eff = coalesce_effective_layout(raw)
    assert custom is True
    assert eff == raw
