from __future__ import annotations

from datetime import datetime, timezone

from fastapi import APIRouter, Depends, Request

from dependencies import (
    get_auth_session,
    get_navigation_service,
    require_authenticated_user,
)
from models import User
from schemas.navigation import (
    NavigationGroupSchema,
    NavigationLinkSchema,
    NavigationSidebarResponse,
)
from services.navigation import NavigationGroupDTO, NavigationLinkDTO, NavigationService
from services.session import AuthSession

router = APIRouter(prefix="/navigation", tags=["Navigation"])


def _to_link_schema(dto: NavigationLinkDTO) -> NavigationLinkSchema:
    return NavigationLinkSchema(
        id=dto.id,
        label=dto.label,
        href=dto.href,
        match_prefix=dto.match_prefix,
        icon=dto.icon,
        tooltip=dto.tooltip,
        is_external=dto.is_external,
        children=[_to_link_schema(child) for child in dto.children],
    )


def _to_group_schema(dto: NavigationGroupDTO) -> NavigationGroupSchema:
    return NavigationGroupSchema(
        id=dto.id,
        label=dto.label,
        icon=dto.icon,
        tooltip=dto.tooltip,
        links=[_to_link_schema(link) for link in dto.links],
    )


@router.get(
    "/sidebar",
    response_model=NavigationSidebarResponse,
    name="navigation.sidebar",
)
async def get_sidebar_navigation(
    request: Request,
    _: User = Depends(require_authenticated_user),
    session: AuthSession = Depends(get_auth_session),
    service: NavigationService = Depends(get_navigation_service),
) -> NavigationSidebarResponse:
    dto = service.build_sidebar(session=session, request=request)
    return NavigationSidebarResponse(
        groups=[_to_group_schema(group) for group in dto.groups],
        roles=list(dto.roles),
        generated_at=datetime.now(tz=timezone.utc),
    )
