from __future__ import annotations

from typing import Annotated

from fastapi import FastAPI, Header

from app.api.deps import CurrentUserContext, get_current_user


def install_legacy_header_auth_override(app: FastAPI) -> None:
    """让领域接口测试专注业务断言，不把旧请求头带回生产认证链路。"""
    app.dependency_overrides[get_current_user] = _read_test_user_headers


def _read_test_user_headers(
    username: Annotated[str | None, Header(alias="X-Auth-Username")] = None,
    name: Annotated[str | None, Header(alias="X-Auth-Name")] = None,
    role_codes: Annotated[str | None, Header(alias="X-Auth-Role-Codes")] = None,
    is_admin: Annotated[str | None, Header(alias="X-Auth-Is-Admin")] = None,
    department: Annotated[str | None, Header(alias="X-Auth-Department")] = None,
    cost_center: Annotated[str | None, Header(alias="X-Auth-Cost-Center")] = None,
    position: Annotated[str | None, Header(alias="X-Auth-Position")] = None,
    grade: Annotated[str | None, Header(alias="X-Auth-Grade")] = None,
    employee_no: Annotated[str | None, Header(alias="X-Auth-Employee-No")] = None,
    manager_name: Annotated[str | None, Header(alias="X-Auth-Manager-Name")] = None,
    tenant_id: Annotated[str | None, Header(alias="X-Auth-Tenant-Id")] = None,
    employee_id: Annotated[str | None, Header(alias="X-Auth-Employee-Id")] = None,
    auth_session_id: Annotated[str | None, Header(alias="X-Auth-Session-Id")] = None,
) -> CurrentUserContext:
    normalized_username = str(username or "").strip()
    normalized_name = str(name or normalized_username).strip()
    if not normalized_username and not normalized_name:
        normalized_username = "test-admin"
        normalized_name = "Test Admin"
        is_admin = "true"

    normalized_roles = [
        normalized
        for item in str(role_codes or "").split(",")
        if (normalized := item.strip().lower())
    ]
    admin_flag = str(is_admin or "").strip().lower() in {"1", "true", "yes", "on"}
    admin_flag = admin_flag or normalized_username.lower() in {"admin", "superadmin"}
    admin_flag = admin_flag or bool(set(normalized_roles) & {"admin", "superadmin"})
    return CurrentUserContext(
        username=normalized_username or normalized_name,
        name=normalized_name or normalized_username,
        role_codes=normalized_roles,
        is_admin=admin_flag,
        tenant_id=str(tenant_id or "default").strip() or "default",
        department_name=str(department or "").strip(),
        cost_center=str(cost_center or "").strip(),
        position=str(position or "").strip(),
        grade=str(grade or "").strip(),
        employee_no=str(employee_no or "").strip(),
        manager_name=str(manager_name or "").strip(),
        employee_id=str(employee_id or "").strip(),
        auth_session_id=str(auth_session_id or "").strip(),
    )
