"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.getApplicationMonitoringDetails = void 0;
const drizzle_orm_1 = require("drizzle-orm");
const database_1 = require("../../../database");
const tables_1 = require("../../../database/tables");
const logger_1 = __importDefault(require("../../../logger"));
const SecretProviderService_1 = require("../../../util/secrets/SecretProviderService");
const getApplicationMonitoringDetails = async (req, res) => {
    try {
        const applicationId = req.query.applicationId;
        if (!applicationId) {
            res.status(400).json({
                success: false,
                message: 'applicationId is required',
            });
            return;
        }
        const db = await (0, database_1.getDb)();
        const monitoringRecords = await db
            .select()
            .from(tables_1.pulseMonitoringTable)
            .where((0, drizzle_orm_1.eq)(tables_1.pulseMonitoringTable.applicationId, applicationId));
        const secretProvider = new SecretProviderService_1.SecretProviderService({
            cloudProvider: process.env.CLOUD_PROVIDER || 'azure',
            vault: process.env.DEFAULT_AZURE_VAULT || 'sccentralindiadev',
            region: process.env.DEFAULT_AZURE_REGION || 'ap-south-1',
        });
        const enrichedRecords = await Promise.all(monitoringRecords.map(async (rec) => {
            const provider = typeof rec?.serviceProvider === 'string'
                ? rec.serviceProvider.toLowerCase()
                : '';
            // `createMonitoring` stores secrets under this deterministic name.
            // Some rows may have an empty `secretName` (older data / partial updates),
            // so we fall back to the convention instead of skipping enrichment.
            const secretNameFromDb = rec?.secretName;
            const secretName = typeof secretNameFromDb === 'string' && secretNameFromDb.trim().length > 0
                ? secretNameFromDb.trim()
                : `pulse-monitoring-${applicationId}`;
            // IMPORTANT: do not return raw secrets to the client.
            // Always return non-secret fields (e.g. region) when available and masked placeholders
            // for secret values so the UI can safely display "****".
            try {
                const secrets = await secretProvider.getAll(secretName, true);
                if (provider === 'aws') {
                    const awsRegion = secrets?.AWS_REGION ?? secrets?.awsRegion ?? rec?.awsRegion;
                    return {
                        ...rec,
                        awsRegion: typeof awsRegion === 'string' ? awsRegion : rec?.awsRegion ?? null,
                        accessKey: secrets?.AWS_ACCESS_KEY_ID ? '****' : (rec?.accessKey ?? '****'),
                        secretKey: secrets?.AWS_SECRET_ACCESS_KEY ? '****' : (rec?.secretKey ?? '****'),
                    };
                }
                if (provider === 'azure') {
                    return {
                        ...rec,
                        clientId: secrets?.AZURE_CLIENT_ID ? String(secrets.AZURE_CLIENT_ID) : rec?.clientId,
                        tenantId: secrets?.AZURE_TENANT_ID ? String(secrets.AZURE_TENANT_ID) : rec?.tenantId,
                        clientSecret: secrets?.AZURE_CLIENT_SECRET ? '****' : (rec?.clientSecret ?? '****'),
                    };
                }
                return rec;
            }
            catch (err) {
                logger_1.default.warn(`Failed to fetch monitoring secret ${secretName}: ${err}`);
                if (provider === 'aws') {
                    return {
                        ...rec,
                        awsRegion: rec?.awsRegion ?? null,
                        accessKey: rec?.accessKey ?? '****',
                        secretKey: rec?.secretKey ?? '****',
                    };
                }
                if (provider === 'azure') {
                    return {
                        ...rec,
                        clientSecret: rec?.clientSecret ?? '****',
                    };
                }
                return rec;
            }
        }));
        logger_1.default.info(`Fetched ${monitoringRecords.length} monitoring records for application ${applicationId}`);
        res.json({
            success: true,
            data: enrichedRecords,
        });
    }
    catch (error) {
        logger_1.default.error(`Error fetching application monitoring details: ${error}`);
        res.status(500).json({
            success: false,
            message: 'Failed to fetch application monitoring details',
        });
    }
};
exports.getApplicationMonitoringDetails = getApplicationMonitoringDetails;
//# sourceMappingURL=get-application-monitoring-details.js.map