import logging

from typing import Optional, NamedTuple, Iterable

from .base import BaseClient
from watcher.config import settings

logger = logging.getLogger(__name__)


class StaffInfo(NamedTuple):
    login: str
    uid: str


class StaffApiClient(BaseClient):

    TVM2_CLIENT = 'staff-api'
    HOST = settings.STAFF_API_HOST

    def get_by_telegram(self, username: str) -> Optional[StaffInfo]:
        logger.info(f'Getting staff by username: {username}')
        response = self._make_request(
            path='/v3/persons/',
            params={
                'telegram_accounts.value': username,
                '_fields': 'uid,login'
            },
        )
        data = response.json().get('result')
        if data:
            if len(data) > 1:
                logger.warning(f'Got multiple staff users by {username}')
                return
            uid = data[0]['uid']
            logger.info(f'Got {uid} by {username}')
            return StaffInfo(uid=uid, login=data[0]['login'])
        logger.info(f'Got no results by {username}')

    def get_telegrams_by_logins(self, logins: Iterable[str], limit: int = 100) -> list[dict]:
        response = self._make_request(
            path='/v3/persons/',
            params={
                'login': ','.join(logins),
                '_fields': 'telegram_accounts.value,login',
                '_limit': limit,
            },
        )
        data = response.json().get('result', [])
        return data


staff_api_client = StaffApiClient()
