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

const router = express.Router();

// GET public platform settings (currency, enabled gateways)
router.get('/public', async (req, res) => {
    try {
        const settings = await AdminSettings.findOne();
        if (!settings) {
            return res.status(200).json({
                status: 'success',
                data: {
                    currency: 'USD',
                    supportEmail: 'support@intellicall.ai',
                    gateways: {
                        stripe: false,
                        paypal: false,
                        dodopayments: false,
                        razorpay: false
                    }
                }
            });
        }

        res.status(200).json({
            status: 'success',
            data: {
                currency: settings.currency,
                supportEmail: settings.supportEmail || 'support@intellicall.ai',
                gateways: {
                    stripe: settings.gateways?.stripe?.enabled || false,
                    stripeTestMode: settings.gateways?.stripe?.testMode ?? true,
                    paypal: settings.gateways?.paypal?.enabled || false,
                    paypalTestMode: settings.gateways?.paypal?.testMode ?? true,
                    paypalClientId: settings.gateways?.paypal?.clientId || '',
                    dodopayments: settings.gateways?.dodopayments?.enabled || false,
                    dodopaymentsTestMode: settings.gateways?.dodopayments?.testMode ?? true,
                    razorpay: settings.gateways?.razorpay?.enabled || false,
                    razorpayTestMode: settings.gateways?.razorpay?.testMode ?? true,
                    razorpayKeyId: settings.gateways?.razorpay?.keyId || ''
                }
            }
        });
    } catch (err) {
        res.status(500).json({ status: 'error', message: err.message });
    }
});

// GET configuration status for keys (Per user)
router.get('/config-status', auth, async (req, res) => {
    try {
        const settings = await Settings.findOne({ userId: req.user._id });

        res.status(200).json({
            status: 'success',
            data: {
                isTwilioConfigured: !!(settings?.twilioSid && settings?.twilioToken && settings?.fromNumber),
                isElevenLabsConfigured: !!(settings?.elevenLabsKey),
                isDeepgramConfigured: !!(settings?.deepgramKey),
                isModelConfigured: !!(settings?.openRouterKey)
            }
        });
    } catch (err) {
        res.status(500).json({ status: 'error', message: err.message });
    }
});

// GET current user settings
router.get('/', auth, async (req, res) => {
    try {
        let settings = await Settings.findOne({ userId: req.user._id });

        // If no settings exist yet, create default settings for this user
        if (!settings) {
            settings = await Settings.create({ userId: req.user._id });
        }

        res.status(200).json({
            status: 'success',
            data: { settings }
        });
    } catch (err) {
        res.status(500).json({ status: 'error', message: err.message });
    }
});

// POST/PUT user settings (BYOK)
router.post('/', auth, async (req, res) => {
    const schema = joi.object({
        twilioSid: joi.string().allow(''),
        twilioToken: joi.string().allow(''),
        fromNumber: joi.string().allow(''),
        openRouterKey: joi.string().allow(''),
        elevenLabsKey: joi.string().allow(''),
        deepgramKey: joi.string().allow(''),
        recordingEnabled: joi.boolean(),
        autoAnalysisEnabled: joi.boolean(),
        timeFormat: joi.string().valid('12', '24')
    });

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

        const settings = await Settings.findOneAndUpdate(
            { userId: req.user._id },
            { $set: data },
            { new: true, upsert: true, runValidators: true }
        );

        res.status(200).json({
            status: 'success',
            data: { settings }
        });
    } catch (err) {
        res.status(400).json({ status: 'error', message: err.message });
    }
});

module.exports = router;
