const invoiceService = require('../services/invoiceService');
const pdfService = require('../services/pdfService');
const { sendEmail } = require('../services/emailService');
const fs = require('fs');
const path = require('path');

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

exports.getInvoices = async (req, res) => {
    try {
        const invoices = await invoiceService.getAllInvoices(req.query);
        res.json(invoices);
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};

exports.getInvoice = async (req, res) => {
    try {
        const invoice = await invoiceService.getInvoiceById(req.params.id, req.query.clientId);
        if (!invoice) return res.status(404).json({ message: 'Invoice not found' });
        res.json(invoice);
    } catch (err) {
        res.status(500).json({ error: err.message });
    }
};

exports.convertQuote = async (req, res) => {
    try {
        const invoice = await invoiceService.convertQuote(req.params.quoteId, req.user.id);
        res.status(201).json(invoice);
    } catch (err) {
        res.status(400).json({ error: err.message });
    }
};

exports.markPaid = async (req, res) => {
    try {
        const { bankAccountId, paymentMethod, amount } = req.body;
        const invoice = await invoiceService.markPaid(req.params.id, req.user.id, { bankAccountId, paymentMethod, amount });
        res.json(invoice);
    } catch (err) {
        res.status(400).json({ error: err.message });
    }
};

exports.downloadPDF = async (req, res) => {
    try {
        const invoice = await invoiceService.getInvoiceById(req.params.id, req.query.clientId);
        if (!invoice) 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=Invoice-${invoice.invoiceNumber}.pdf`);

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

const { invoiceEmailTemplate } = require('../utils/emailTemplates');
const { SystemSetting } = require('../models/settings');

exports.sendByEmail = async (req, res) => {
    try {
        const invoice = await invoiceService.getInvoiceById(req.params.id, req.query.clientId);
        if (!invoice) return res.status(404).json({ message: 'Invoice 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
        };

        // Generate PDF Buffer
        const pdfBuffer = await pdfService.generateBuffer('invoice', invoice);

        // Generate HTML
        const html = invoiceEmailTemplate(invoice, invoice.Client, companyProfile);

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

        // Update invoice status to 'Sent' if it was 'Draft'
        if (invoice.status === 'Draft') {
            await invoice.update({ status: 'Sent' });
        }

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

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

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