# Copyright (c) 2022 CloudZero - ALL RIGHTS RESERVED - PROPRIETARY AND CONFIDENTIAL
# Unauthorized copying of this file and/or project, via any medium is strictly prohibited.
# Direct all questions to legal@cloudzero.com

import logging
from typing import List

from aws_lambda_powertools.utilities.parameters import secrets
from msal.application import ConfidentialClientApplication

import czc.constants as constants

AUTHORITY = 'https://login.microsoftonline.com/{tenant_id}'
DEFAULT_SCOPE = ["https://management.azure.com/.default"]

logger = logging.getLogger(constants.PROJECT_NAME)


class AzureAccessTokenException(Exception):
    def __init__(self, error, error_description, correlation_id, *args: object) -> None:
        msg = f'Failed to obtain Azure access token. Error={error}, Description={error_description}, Correlation ID: {correlation_id}'
        logger.error(msg)
        super().__init__(msg)


def get(cloudzero_platform_secret_name, tenant_id: str, scopes: List[str] = None):
    client_info: dict = secrets.get_secret(cloudzero_platform_secret_name, transform='json')  # type:ignore
    app = ConfidentialClientApplication(
        client_id=client_info['client_id'],
        authority=str.format(AUTHORITY, tenant_id=tenant_id),
        client_credential=client_info['secret'])

    if scopes is None:
        scopes = scopes or DEFAULT_SCOPE

    result = app.acquire_token_silent(scopes=scopes, account=None) or app.acquire_token_for_client(scopes=scopes)

    if "access_token" in result:
        return result['access_token']
    else:
        raise AzureAccessTokenException(result.get('error'), result.get('error_description'), result.get('correlation_id'))
