"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.simpleOutboundCallController = void 0;
const twilio_1 = __importDefault(require("twilio"));
const logger_1 = __importDefault(require("../../../logger"));
const { TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN, TWILIO_PHONE_NUMBER, TWILIO_BASE_URL } = process.env;
// Initialize Twilio client
let twilioClient = null;
if (TWILIO_ACCOUNT_SID && TWILIO_AUTH_TOKEN) {
    try {
        twilioClient = (0, twilio_1.default)(TWILIO_ACCOUNT_SID, TWILIO_AUTH_TOKEN);
    }
    catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        logger_1.default.warn(`Failed to initialize Twilio client for simple outbound calls: ${message}`);
        twilioClient = null;
    }
}
/**
 * Controller for initiating a simple outbound call
 */
const simpleOutboundCallController = async (req, res) => {
    if (!twilioClient) {
        res.status(500).json({
            error: 'Twilio client not initialized. Please set TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN in .env file.',
        });
        return;
    }
    if (!TWILIO_PHONE_NUMBER) {
        res.status(500).json({
            error: 'TWILIO_PHONE_NUMBER not set in .env file.',
        });
        return;
    }
    const toNumber = req.body?.to || req.query?.to;
    if (!toNumber) {
        res.status(400).json({
            error: 'Missing "to" parameter. Please provide a phone number to call.',
        });
        return;
    }
    try {
        const baseUrl = TWILIO_BASE_URL || req.headers.origin || `https://${req.headers.host}`;
        const answerUrl = `${baseUrl}/api/phone/outbound-call-answered`;
        // Make the outbound call
        const call = await twilioClient.calls.create({
            to: toNumber,
            from: TWILIO_PHONE_NUMBER,
            url: answerUrl,
            method: 'POST',
            record: true, // Enable call recording
            timeLimit: 180, // 3 minutes (180 seconds) call time limit
        });
        logger_1.default.info(`Outbound call initiated: ${call.sid} to ${toNumber}`);
        res.json({
            success: true,
            callSid: call.sid,
            status: call.status,
            to: toNumber,
            from: TWILIO_PHONE_NUMBER,
            message: 'Call initiated successfully',
        });
    }
    catch (error) {
        logger_1.default.error(`Error initiating outbound call: ${error.message}`);
        // Provide more specific error messages for common Twilio errors
        let errorMessage = error.message || 'Failed to initiate call';
        if (error.status === 401 || error.code === 20003) {
            errorMessage =
                'Twilio authentication failed. Please check your TWILIO_ACCOUNT_SID and TWILIO_AUTH_TOKEN in the .env file.';
        }
        else if (error.status === 400) {
            errorMessage = `Invalid request: ${error.message || 'Please check your phone number format and Twilio configuration.'}`;
        }
        else if (error.status === 403) {
            errorMessage = 'Twilio permission denied. Please check your account permissions.';
        }
        res.status(error.status || 500).json({
            error: 'Failed to initiate call',
            message: errorMessage,
            details: process.env.NODE_ENV === 'development' ? error.stack : undefined,
        });
    }
};
exports.simpleOutboundCallController = simpleOutboundCallController;
//# sourceMappingURL=simple-outbound-call.js.map