"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.AWSSTSProvider = void 0;
/* eslint-disable max-len */
const node_cache_1 = require("../../node-cache");
const lodash_1 = __importDefault(require("lodash"));
const aws_sdk_1 = __importDefault(require("aws-sdk"));
const logger_1 = require("../../../logger");
const AWSSecretManagerProvider_1 = require("../../secrets/providers/AWSSecretManagerProvider");
const AzureKeyVaultSecretProvider_1 = require("../../secrets/providers/AzureKeyVaultSecretProvider");
class AWSSTSProvider {
    constructor(awsConfig, logger = logger_1.logger) {
        this.spydraCache = node_cache_1.NodeCache.getInstance();
        this.logger = logger_1.logger;
        /**
         * Fetches the secret automatically based on the configured provider.
         * If the provider is 'aws', it retrieves the secret from AWS Secret Manager.
         * If the provider is 'azure', it retrieves the secret from Azure Key Vault.
         * Throws an error if the required parameters are not provided.
         */
        this.autoFetchSecret = async () => {
            if (this.shouldAutoFetchSecret
                && this.autoFetchSecretProvider === 'aws') {
                if (lodash_1.default.isEmpty(this.region) && lodash_1.default.isEmpty(this.autoFetchSecretRegion)) {
                    throw new Error('Region is required for aws secret provider');
                }
                const region = this.autoFetchSecretRegion || this.region;
                const cachedSecret = this.spydraCache.get(`${region}-${this.autoFetchSecretName}`);
                if (cachedSecret && lodash_1.default.isEmpty(cachedSecret) === false) {
                    this.accessKey = cachedSecret?.AWS_ACCESS_KEY_ID;
                    this.secretKey = cachedSecret?.AWS_SECRET_ACCESS_KEY;
                }
                else {
                    const awsService = new AWSSecretManagerProvider_1.AWSSecretManagerProvider({
                        region: region,
                        cloudProvider: 'aws',
                    });
                    const secrets = await awsService.getAll(this.autoFetchSecretName);
                    this.accessKey = secrets.AWS_ACCESS_KEY_ID;
                    this.secretKey = secrets.AWS_SECRET_ACCESS_KEY;
                }
            }
            else if (this.shouldAutoFetchSecret
                && this.autoFetchSecretProvider === 'azure') {
                if (lodash_1.default.isEmpty(this.autoFetchSecretVault)) {
                    throw new Error('Vault is required for azure secret provider');
                }
                const cachedSecret = this.spydraCache.get(`${this.autoFetchSecretVault}-${this.autoFetchSecretName}`);
                if (cachedSecret && lodash_1.default.isEmpty(cachedSecret) === false) {
                    this.accessKey = cachedSecret?.AWS_ACCESS_KEY_ID;
                    this.secretKey = cachedSecret?.AWS_SECRET_ACCESS_KEY;
                }
                else {
                    const azureService = new AzureKeyVaultSecretProvider_1.AzureKeyVaultSecretProvider({
                        vault: this.autoFetchSecretVault,
                        region: this.region,
                        secretKey: this.secretKey,
                        accessKey: this.accessKey,
                        autoFetchSecret: this.shouldAutoFetchSecret,
                        autoFetchSecretProvider: this.autoFetchSecretProvider,
                        autoFetchSecretName: this.autoFetchSecretName,
                        cloudProvider: 'azure',
                    });
                    const secrets = await azureService.getAll(this.autoFetchSecretName);
                    this.spydraCache.set(`${this.autoFetchSecretVault}-${this.autoFetchSecretName}`, secrets, 60 * 60);
                    this.accessKey = secrets.AWS_ACCESS_KEY_ID;
                    this.secretKey = secrets.AWS_SECRET_ACCESS_KEY;
                }
            }
        };
        this.verify = async () => {
            const response = {};
            try {
                await this.autoFetchSecret();
                const config = {
                    accessKeyId: this.accessKey,
                    secretAccessKey: this.secretKey,
                };
                const client = new aws_sdk_1.default.STS(config);
                await client.getCallerIdentity({}).promise().then((data) => {
                    if (lodash_1.default.isEmpty(data?.UserId)) {
                        response.apiError = new Error('Unable to verify AWS Credentials');
                    }
                    else {
                        response.apiError = null;
                        response.apiResponse = data;
                    }
                }).catch((error) => {
                    this.logger.error(`Unable to verify credentials: ${error}`);
                    response.apiError = new Error('Unable to verify AWS Credentials');
                });
            }
            catch (error) {
                this.logger.error(`Unable to verify credentials: ${error}`);
                response.apiError = new Error('Unable to verify AWS Credentials');
            }
            return response;
        };
        this.region = awsConfig.region;
        this.accessKey = awsConfig.accessKey;
        this.secretKey = awsConfig.secretKey;
        this.shouldAutoFetchSecret = awsConfig.autoFetchSecret;
        this.autoFetchSecretProvider = awsConfig.autoFetchSecretProvider;
        this.autoFetchSecretVault = awsConfig.autoFetchSecretVault;
        this.autoFetchSecretName = awsConfig.autoFetchSecretName;
        this.autoFetchSecretRegion = awsConfig.autoFetchSecretRegion;
        this.logger = logger;
    }
}
exports.AWSSTSProvider = AWSSTSProvider;
//# sourceMappingURL=AWSSTSProvider.js.map