import msgspec
from httpx import AsyncClient
from .structs import PerunUserStruct

from config import PerunSyncConfig


class PerunSyncClient:
    def __init__(self, config: PerunSyncConfig) -> None:
        self.config = config

    async def get_user_by_email(self, email: str) -> PerunUserStruct | None:
        async with AsyncClient() as client:
            response = await client.get(self.config.url, params={"mail": email}, headers=self.config.auth_headers)
            if not response.is_success:
                return None
            if len(users := msgspec.convert(response.json(), type=list[PerunUserStruct])) > 0 and all(user.login_mu == users[0].login_mu for user in users):
                return users[0]
            return None
