"""Cognito groups → single internal role (priority + mapping)."""

from tradekartauth.config import CLAIM_GROUPS, ROLE_ADMIN, ROLE_TRADER, ROLE_VIEWER, CognitoAuthConfig
from tradekartauth.services.role_mapper import RoleMapper, resolve_role_from_claims


def _cfg(**kwargs: object) -> CognitoAuthConfig:
    base: dict = {"user_pool_id": "ap-south-1_test", "region": "ap-south-1"}
    base.update(kwargs)
    return CognitoAuthConfig(**base)


def test_priority_admin_wins() -> None:
    claims = {CLAIM_GROUPS: ["viewer", "trader", "admin"]}
    assert resolve_role_from_claims(claims, _cfg()) == ROLE_ADMIN


def test_case_insensitive_group_names() -> None:
    claims = {CLAIM_GROUPS: ["TrAdEr"]}
    assert resolve_role_from_claims(claims, _cfg()) == ROLE_TRADER


def test_group_to_role_mapping() -> None:
    claims = {CLAIM_GROUPS: ["tk-admins"]}
    cfg = _cfg(group_to_role={"tk-admins": ROLE_ADMIN})
    assert resolve_role_from_claims(claims, cfg) == ROLE_ADMIN


def test_no_groups() -> None:
    assert resolve_role_from_claims({}, _cfg()) is None


def test_groups_empty_list() -> None:
    assert resolve_role_from_claims({CLAIM_GROUPS: []}, _cfg()) is None


def test_role_mapper_class_wrapper() -> None:
    cfg = _cfg()
    mapper = RoleMapper(cfg)
    assert mapper.map_role({CLAIM_GROUPS: ["admin"]}) == ROLE_ADMIN


def test_unknown_group_names_ignored() -> None:
    claims = {CLAIM_GROUPS: ["random-ldap-group"]}
    assert resolve_role_from_claims(claims, _cfg()) is None
