const quoteService = require('../services/quoteService');
const pdfService = require('../services/pdfService');
const { sendEmail } = require('../services/emailService');
const { quoteEmailTemplate } = require('../utils/emailTemplates');
const { SystemSetting } = require('../models/settings');

exports.createQuote = async (req, res) => {
    try {
        const quote = await quoteService.createQuote(req.body, req.user.id);
        res.status(201).json(quote);
    } catch (err) {
        res.status(400).json({ error: err.message });
    }
};

exports.getQuotes = async (req, res) => {
    try {
        const quotes = await quoteService.getAllQuotes(req.query);
        res.json(quotes);
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};

exports.getQuote = async (req, res) => {
    try {
        const quote = await quoteService.getQuoteById(req.params.id, req.query.clientId);
        if (!quote) return res.status(404).json({ message: 'Not found' });
        res.json(quote);
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};

exports.sendByEmail = async (req, res) => {
    try {
        const quote = await quoteService.getQuoteById(req.params.id, req.query.clientId);
        if (!quote) return res.status(404).json({ message: 'Quote not found' });

        // Fetch all system settings for company profile
        const settings = await SystemSetting.findAll();
        const settingsMap = {};
        settings.forEach(s => settingsMap[s.key] = s.value);

        const companyProfile = {
            name: settingsMap['COMPANY_NAME'],
            website: settingsMap['COMPANY_WEBSITE'],
            currency: settingsMap['DEFAULT_CURRENCY'] || 'KES',
            logoUrl: settingsMap['COMPANY_LOGO'] ? `${process.env.APP_URL || 'http://localhost:5000'}${settingsMap['COMPANY_LOGO']}` : null
        };

        const pdfBuffer = await pdfService.generateBuffer('quote', quote);
        const html = quoteEmailTemplate(quote, quote.Client, companyProfile);

        await sendEmail({
            to: quote.Client.email,
            subject: `Quote ${quote.quoteNumber} from ${companyProfile.name || 'Finance Pro'}`,
            html: html,
            attachments: [
                {
                    filename: `Quote-${quote.quoteNumber}.pdf`,
                    content: pdfBuffer
                }
            ],
            module: 'QUOTE',
            referenceId: quote.id
        });

        if (quote.status === 'Draft') {
            await quote.update({ status: 'Sent' });
        }

        res.json({ message: 'Email sent successfully' });
    } catch (err) {
        console.error('Send quote email error:', err);
        res.status(500).json({ error: err.message });
    }
};

exports.updateStatus = async (req, res) => {
    try {
        const quote = await quoteService.updateQuoteStatus(req.params.id, req.body.status, req.user.id);
        res.json(quote);
    } catch (err) {
        res.status(400).json({ error: err.message });
    }
};

exports.downloadPDF = async (req, res) => {
    try {
        const quote = await quoteService.getQuoteById(req.params.id, req.query.clientId);
        if (!quote) return res.status(404).json({ message: 'Not found' });

        const disposition = req.query.mode === 'view' ? 'inline' : 'attachment';
        res.setHeader('Content-Type', 'application/pdf');
        res.setHeader('Content-Disposition', `${disposition}; filename=Quote-${quote.quoteNumber}.pdf`);

        await pdfService.generateBillingPDF('quote', quote, res);
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};

exports.updateQuote = async (req, res) => {
    try {
        const quote = await quoteService.updateQuote(req.params.id, req.body, req.user.id);
        res.json(quote);
    } catch (err) {
        res.status(400).json({ error: err.message });
    }
};

exports.deleteQuote = async (req, res) => {
    try {
        await quoteService.deleteQuote(req.params.id, req.user.id);
        res.json({ message: 'Quote deleted successfully' });
    } catch (err) {
        res.status(400).json({ error: err.message });
    }
};
