const express = require('express');
const twilio = require('twilio');
const { auth } = require('../middleware/auth');
const Settings = require('../models/Settings');
const Agent = require('../models/Agent');
const Lead = require('../models/Lead');
const joi = require('joi');

const router = express.Router();

// POST /api/calls/test
// Trigger a test call using stored Twilio credentials
router.post('/test', auth, async (req, res) => {
    const schema = joi.object({
        to: joi.string().required().description('Destination phone number in E.164 format')
    });

    try {
        const { to } = await schema.validateAsync(req.body);

        // Fetch global settings
        const settings = await Settings.findOne({ userId: req.user._id });

        if (!settings || !settings.twilioSid || !settings.twilioToken || !settings.fromNumber) {
            return res.status(400).json({
                status: 'error',
                message: 'Twilio credentials not configured. Please visit Settings.'
            });
        }

        const client = twilio(settings.twilioSid, settings.twilioToken);

        // Simple TwiML for the test call
        const twiml = new twilio.twiml.VoiceResponse();
        twiml.say('Hello from IntelliCall AI. This is a test call to verify your Twilio integration. Your settings are configured correctly. Goodbye!');

        const call = await client.calls.create({
            twiml: twiml.toString(),
            to: to,
            from: settings.fromNumber
        });

        res.status(200).json({
            status: 'success',
            message: 'Test call initiated',
            data: {
                callSid: call.sid,
                status: call.status
            }
        });
    } catch (err) {
        console.error('Twilio Test Call Error:', err);
        res.status(err.status || 500).json({
            status: 'error',
            message: err.message || 'Failed to initiate test call'
        });
    }
});

// POST /api/calls/ai-test
// Trigger a full AI conversation test call using webhooks
router.post('/ai-test', auth, async (req, res) => {
    const schema = joi.object({
        to: joi.string().required()
    });

    try {
        const { to } = await schema.validateAsync(req.body);

        const settings = await Settings.findOne({ userId: req.user._id });
        const [agent, lead] = await Promise.all([
            Agent.findOne({ createdBy: req.user._id }),
            Lead.findOne({})
        ]);

        if (!settings || !settings.twilioSid || !settings.twilioToken || !settings.fromNumber) {
            return res.status(400).json({
                status: 'error',
                message: 'Twilio credentials not configured'
            });
        }

        if (!agent || !lead) {
            return res.status(400).json({
                status: 'error',
                message: 'Need at least one Agent and one Lead to run AI test'
            });
        }

        const client = twilio(settings.twilioSid, settings.twilioToken);
        const baseUrl = process.env.BASE_URL || `http://${req.get('host')}`;

        const call = await client.calls.create({
            url: `${baseUrl}/api/twilio/voice?userId=${req.user._id}&agentId=${agent._id}&leadId=${lead._id}`,
            to: to,
            from: settings.fromNumber,
            record: settings.recordingEnabled ?? true,
            statusCallback: `${baseUrl}/api/twilio/status`,
            statusCallbackMethod: 'POST',
            statusCallbackEvent: ['initiated', 'ringing', 'answered', 'completed']
        });

        res.status(200).json({
            status: 'success',
            message: 'AI Conversation test initiated',
            data: { callSid: call.sid }
        });
    } catch (err) {
        console.error('Twilio AI Test Error:', err);
        res.status(err.status || 500).json({
            status: 'error',
            message: err.message || 'Failed to initiate AI test call'
        });
    }
});

module.exports = router;
