"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.testGatewayConnection = exports.deleteGateway = exports.toggleGateway = exports.updateGatewayConfig = exports.createGatewayConfig = exports.getAdminGateways = exports.getPublicGateways = void 0;
const database_1 = __importDefault(require("../../../config/database"));
const response_utils_1 = require("../../../utils/response.utils");
const encryption_utils_1 = require("../../../utils/encryption.utils");
const logger_1 = require("../../../config/logger");
// 1. Public Gateway Settings List (enabled checkout payment systems only, no secrets exposed)
const getPublicGateways = async (_req, res) => {
    try {
        const settings = await database_1.default.paymentGatewaySetting.findMany({
            where: { isEnabled: true },
            orderBy: { sortOrder: 'asc' },
            select: {
                id: true,
                gatewayName: true,
                displayName: true,
                environment: true,
                currency: true,
                minAmount: true,
                maxAmount: true,
                processingFee: true,
                sortOrder: true,
            },
        });
        return (0, response_utils_1.sendSuccess)(res, 'Active checkout payment options retrieved', { gateways: settings });
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Failed to retrieve payment gateways', error.message, 500);
    }
};
exports.getPublicGateways = getPublicGateways;
// 2. Admin Gateways Settings List (Masked credentials)
const getAdminGateways = async (req, res) => {
    try {
        // Only ADMIN role authorized
        if (res.locals.userRole !== 'ADMIN' && req.user?.role !== 'ADMIN') {
            return (0, response_utils_1.sendError)(res, 'Unauthorized to view credentials settings', null, 403);
        }
        const settings = await database_1.default.paymentGatewaySetting.findMany({
            orderBy: { sortOrder: 'asc' },
        });
        // Mask sensitive configurations for security audit
        const maskedSettings = settings.map((s) => ({
            ...s,
            keySecret: s.keySecret ? (0, encryption_utils_1.maskSecret)(s.keySecret) : null,
            clientSecret: s.clientSecret ? (0, encryption_utils_1.maskSecret)(s.clientSecret) : null,
            saltKey: s.saltKey ? (0, encryption_utils_1.maskSecret)(s.saltKey) : null,
            webhookSecret: s.webhookSecret ? (0, encryption_utils_1.maskSecret)(s.webhookSecret) : null,
        }));
        return (0, response_utils_1.sendSuccess)(res, 'Admin payment configurations retrieved', { gateways: maskedSettings });
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Admin retrieval failed', error.message, 500);
    }
};
exports.getAdminGateways = getAdminGateways;
// 3. Create Gateway configuration
const createGatewayConfig = async (req, res) => {
    try {
        const { gatewayName, displayName, isEnabled, environment, merchantId, clientId, clientSecret, keyId, keySecret, saltKey, saltIndex, webhookSecret, callbackUrl, webhookUrl, currency, minAmount, maxAmount, processingFee, sortOrder, } = req.body;
        const gateway = await database_1.default.paymentGatewaySetting.create({
            data: {
                gatewayName: gatewayName.toUpperCase(),
                displayName,
                isEnabled: isEnabled ?? true,
                environment: environment || 'sandbox',
                merchantId,
                clientId,
                clientSecret: clientSecret ? (0, encryption_utils_1.encrypt)(clientSecret) : null,
                keyId,
                keySecret: keySecret ? (0, encryption_utils_1.encrypt)(keySecret) : null,
                saltKey: saltKey ? (0, encryption_utils_1.encrypt)(saltKey) : null,
                saltIndex,
                webhookSecret: webhookSecret ? (0, encryption_utils_1.encrypt)(webhookSecret) : null,
                callbackUrl,
                webhookUrl,
                currency: currency || 'INR',
                minAmount: minAmount ?? 1.0,
                maxAmount: maxAmount ?? 500000.0,
                processingFee: processingFee ?? 0.0,
                sortOrder: sortOrder ?? 0,
            },
        });
        return (0, response_utils_1.sendSuccess)(res, 'Gateway configuration created successfully', { id: gateway.id });
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Failed to create configuration', error.message, 500);
    }
};
exports.createGatewayConfig = createGatewayConfig;
// 4. Update Gateway credentials configuration (Encrypting sensitive fields)
const updateGatewayConfig = async (req, res) => {
    try {
        const { id } = req.params;
        const body = req.body;
        const existing = await database_1.default.paymentGatewaySetting.findUnique({ where: { id } });
        if (!existing)
            return (0, response_utils_1.sendError)(res, 'Gateway configuration not found', null, 404);
        // Keep decrypted secret if it is still masked (************) in the update request
        const clientSecret = body.clientSecret === '************' ? existing.clientSecret : (body.clientSecret ? (0, encryption_utils_1.encrypt)(body.clientSecret) : null);
        const keySecret = body.keySecret === '************' ? existing.keySecret : (body.keySecret ? (0, encryption_utils_1.encrypt)(body.keySecret) : null);
        const saltKey = body.saltKey === '************' ? existing.saltKey : (body.saltKey ? (0, encryption_utils_1.encrypt)(body.saltKey) : null);
        const webhookSecret = body.webhookSecret === '************' ? existing.webhookSecret : (body.webhookSecret ? (0, encryption_utils_1.encrypt)(body.webhookSecret) : null);
        await database_1.default.paymentGatewaySetting.update({
            where: { id },
            data: {
                displayName: body.displayName,
                isEnabled: body.isEnabled,
                environment: body.environment,
                merchantId: body.merchantId,
                clientId: body.clientId,
                clientSecret,
                keyId: body.keyId,
                keySecret,
                saltKey,
                saltIndex: body.saltIndex,
                webhookSecret,
                callbackUrl: body.callbackUrl,
                webhookUrl: body.webhookUrl,
                currency: body.currency,
                minAmount: body.minAmount,
                maxAmount: body.maxAmount,
                processingFee: body.processingFee,
                sortOrder: body.sortOrder,
            },
        });
        // Write audit log
        await database_1.default.activityLog.create({
            data: {
                adminId: req.user?.adminId,
                action: 'PAYMENT_GATEWAY_CONFIG_UPDATED',
                details: { gatewayName: existing.gatewayName },
            },
        });
        logger_1.logger.info(`Payment Gateway configuration updated for: ${existing.gatewayName}`);
        return (0, response_utils_1.sendSuccess)(res, 'Gateway configuration updated successfully');
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Update failed', error.message, 500);
    }
};
exports.updateGatewayConfig = updateGatewayConfig;
// 5. Toggle enable / disable status
const toggleGateway = async (req, res) => {
    try {
        const { id } = req.params;
        const existing = await database_1.default.paymentGatewaySetting.findUnique({ where: { id } });
        if (!existing)
            return (0, response_utils_1.sendError)(res, 'Gateway not found', null, 404);
        const updated = await database_1.default.paymentGatewaySetting.update({
            where: { id },
            data: { isEnabled: !existing.isEnabled },
        });
        return (0, response_utils_1.sendSuccess)(res, `Gateway status toggled to: ${updated.isEnabled ? 'Enabled' : 'Disabled'}`, { isEnabled: updated.isEnabled });
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Toggle failed', error.message, 500);
    }
};
exports.toggleGateway = toggleGateway;
// 6. Delete config
const deleteGateway = async (req, res) => {
    try {
        const { id } = req.params;
        await database_1.default.paymentGatewaySetting.delete({ where: { id } });
        return (0, response_utils_1.sendSuccess)(res, 'Gateway configuration deleted successfully');
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Deletion failed', error.message, 500);
    }
};
exports.deleteGateway = deleteGateway;
// 7. Connection status check / Test connection api
const testGatewayConnection = async (req, res) => {
    try {
        const { id } = req.params;
        const gateway = await database_1.default.paymentGatewaySetting.findUnique({ where: { id } });
        if (!gateway)
            return (0, response_utils_1.sendError)(res, 'Gateway configuration not found', null, 404);
        // Mock API connection request depending on gateway keys.
        // If key ID starts with "invalid" or keys are empty, connection fails.
        const isSuccess = gateway.keyId !== 'invalid' && (gateway.isEnabled || gateway.displayName !== '');
        logger_1.logger.info(`Tested gateway connection for ${gateway.gatewayName}: ${isSuccess ? 'CONNECTED' : 'FAILED'}`);
        return (0, response_utils_1.sendSuccess)(res, 'Tested connection parameters', {
            connected: isSuccess,
            status: isSuccess ? 'Connected' : 'Failed',
        });
    }
    catch (error) {
        return (0, response_utils_1.sendError)(res, 'Connection test failed', error.message, 500);
    }
};
exports.testGatewayConnection = testGatewayConnection;
//# sourceMappingURL=gateway-config.controller.js.map