# coding: utf-8

from typing import List

import requests
from django.conf import settings


def oebs_request(method: str, path: str, **kwargs) -> requests.Response:
    kwargs = kwargs.copy()
    kwargs.update(settings.OEBS_PARAMS)
    return requests.request(
        method, f'{settings.OEBS_API_PREFIX}{path}', **kwargs
    )


class OEBSError(Exception):
    pass


def get_approvers(
    org_id, cfo, *, project=None, task=None, mvp=None, service=None
) -> List[str]:

    data = {
        'org_id': org_id,
        'cfo': cfo,
        'project': project,
        'task': task,
        'mvp': mvp,
        'service': service,
    }

    data = dict(x for x in data.items() if x[1] is not None)

    req = oebs_request('post', '/getApprover', json=data)

    try:
        data = req.json()

        if data.get('status') == 'OK':
            usernames = data.get('login', [])
            usernames = map(str.lower, usernames)
            return list(usernames)

        else:
            raise OEBSError(data.get('message', 'Unknown error'))

    except ValueError:
        raise OEBSError('Fetch error')
