"""
Nom du script : gitlab_user_service.py
Chemin : /gitlab-bridge/app/services/gitlab_user_service.py
Description : Résolution sécurisée du compte GitLab à partir du username et de l'email.
Options éventuelles : Aucune.
Exemples d'utilisation : `GitLabUserService(client).resolve_user(...)`.
Prérequis : Python 3.11+.
Auteur : Sylvain SCATTOLINI
Date de création / modification : 2026-03-25
Version : 1.1
"""

from __future__ import annotations

from app.clients.gitlab_client import GitLabClient
from app.core.exceptions import GitLabUserNotFoundError
from app.schemas.common import AuthContext


class GitLabUserService:
    """Résout un utilisateur GitLab de manière défensive."""

    def __init__(self, client: GitLabClient) -> None:
        self.client = client

    def resolve_user(self, auth: AuthContext) -> dict:
        candidates = self.client.search_users(email=auth.email)
        user = self._select_user(candidates, auth)
        if user is not None:
            return user

        candidates = self.client.search_users(username=auth.username)
        user = self._select_user(candidates, auth)
        if user is not None:
            return user

        raise GitLabUserNotFoundError()

    @staticmethod
    def _select_user(candidates: list[dict], auth: AuthContext) -> dict | None:
        for candidate in candidates:
            candidate_username = str(candidate.get('username', '')).strip().lower()
            candidate_email = str(candidate.get('public_email', '') or candidate.get('email', '')).strip().lower()
            if candidate_username == auth.username or candidate_email == auth.email:
                return candidate
        return None
