const { SystemSetting } = require('../models/settings');
const { encrypt, decrypt } = require('../utils/crypto');
const emailService = require('../services/emailService');

const SENSITIVE_KEYS = ['EMAIL_PASSWORD', 'SMS_API_KEY'];

// Public endpoint - no auth required
exports.getPublicBranding = async (req, res) => {
    try {
        const settings = await SystemSetting.findAll({
            where: {
                key: ['COMPANY_NAME', 'COMPANY_LOGO']
            }
        });
        const brandingMap = {};
        settings.forEach(s => {
            brandingMap[s.key] = s.value;
        });
        res.json(brandingMap);
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};

exports.getSettings = async (req, res) => {
    try {
        const settings = await SystemSetting.findAll();
        const settingsMap = {};
        settings.forEach(s => {
            if (SENSITIVE_KEYS.includes(s.key) && s.value) {
                // We send a placeholder to the frontend for sensitive keys if they exist
                settingsMap[s.key] = '********';
            } else {
                settingsMap[s.key] = s.value;
            }
        });
        res.json(settingsMap);
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};

exports.updateSettings = async (req, res) => {
    try {
        const settings = req.body;
        for (const [key, value] of Object.entries(settings)) {
            let valueToStore = value;
            if (SENSITIVE_KEYS.includes(key)) {
                // If it's a placeholder, don't update it
                if (value === '********') continue;
                valueToStore = encrypt(value);
            }
            await SystemSetting.upsert({ key, value: valueToStore });
        }
        res.json({ message: 'Settings updated successfully' });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};

exports.testEmail = async (req, res) => {
    try {
        const { testEmail } = req.body;
        await emailService.sendEmail({
            to: testEmail,
            subject: 'Test Email - Finance System',
            html: `
                <div style="font-family: sans-serif; padding: 20px; border: 1px solid #eee; border-radius: 10px; max-width: 500px; margin: 0 auto; background-color: #fff;">
                    <div style="text-align: center; margin-bottom: 20px;">
                        <h1 style="color: #4f46e5; margin: 0;">Finance System</h1>
                        <p style="color: #64748b; font-size: 14px;">Email Configuration Test</p>
                    </div>
                    <div style="padding: 20px; background-color: #f8fafc; rounded: 8px;">
                        <h2 style="color: #0f172a; font-size: 18px; margin-top: 0;">Connection Successful!</h2>
                        <p style="color: #475569; line-height: 1.6;">Your email configuration is working correctly. You can now send invoices and notifications securely through this system.</p>
                    </div>
                    <p style="text-align: center; color: #94a3b8; font-size: 12px; margin-top: 30px;">
                        Sent at: ${new Date().toLocaleString()}<br>
                        This is an automated test email.
                    </p>
                </div>
            `
        });
        res.json({ message: 'Test email sent successfully' });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};

exports.uploadLogo = async (req, res) => {
    try {
        if (!req.file) {
            return res.status(400).json({ error: 'No file uploaded' });
        }

        const logoUrl = `/uploads/${req.file.filename}`;

        // Update the setting in the DB
        await SystemSetting.upsert({
            key: 'COMPANY_LOGO',
            value: logoUrl,
            description: 'System Company Logo'
        });

        res.json({
            message: 'Logo uploaded successfully',
            logoUrl
        });
    } catch (err) {
        console.error(err);
        res.status(500).json({ error: 'Failed to upload logo' });
    }
};

const { TaxRate } = require('../models/settings');

exports.getTaxRates = async (req, res) => {
    try {
        const rates = await TaxRate.findAll({ where: { isActive: true } });
        res.json(rates);
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};

exports.createTaxRate = async (req, res) => {
    try {
        const rate = await TaxRate.create(req.body);
        res.status(201).json(rate);
    } catch (err) {
        res.status(400).json({ error: err.message });
    }
};

exports.deleteTaxRate = async (req, res) => {
    try {
        const rate = await TaxRate.findByPk(req.params.id);
        if (!rate) return res.status(404).json({ message: 'Not found' });
        rate.isActive = false; // Soft delete
        await rate.save();
        res.json({ message: 'Tax rate deleted' });
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};
