import json
from typing import List

from django.conf import settings
from django.core.exceptions import ValidationError

from staff.lib.requests import Session


star_trek_session = Session()
star_trek_session.headers.update({
    'Authorization': f'OAuth {settings.ROBOT_STAFF_OAUTH_TOKEN}',
    'Content-type': 'application/json',
})


class StarTrekLoginExistenceValidator:
    _issues_url = f'{settings.STARTREK_API_URL}/v2/issues/'

    def validate_logins(self, logins: List[str]) -> None:
        probe_data = {
            'queue': 'STAFF',
            'summary': 'summary',
            'employees': logins,
            'author': 'жопа с ручкой',
        }

        star_trek_response = star_trek_session.post(self._issues_url, data=json.dumps(probe_data))

        if star_trek_response.status_code != 422:
            raise ValidationError(
                'Star Trek unexpected response',
                code='unexpected_star_trek_response',
            )

        employees_error = star_trek_response.json()['errors'].get('employees', None)

        if employees_error:
            raise ValidationError(
                'Some logins are not in Star Trek',
                code='logins_not_in_star_trek',
                params=employees_error,
            )
