# Copyright (c) 2021 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

from functools import partial

import boto3
from czc.dynamodb import compose_key, prefix, query

LATEST = 'latest'
dynamodb = boto3.resource('dynamodb')
prefix_organization = partial(prefix, 'organization')
prefix_data = partial(prefix, 'data')
prefix_api_key = partial(prefix, 'api-key')


def fetch(namespace: str, organization_id: str):
    table_name = f'cz-{namespace}-identity-data'
    table = dynamodb.Table(table_name)
    query_kwargs = {
        'KeyConditionExpression': '#pk = :pk AND begins_with(#sk, :sk)',
        'ExpressionAttributeNames': {'#pk': 'PK', '#sk': 'SK'},
        'ExpressionAttributeValues': {
            ':pk': prefix_organization(organization_id),
            ':sk': compose_key('api-key', 'v', LATEST),
        }
    }

    [item] = query(table, query_kwargs)
    return item['api_key']
