const InvoiceService = require('../../services/invoice/InvoiceService');
const service = new InvoiceService();

module.exports = {
  async listMine(req, res) {
    try {
      const data = await service.listMine(req.user.id, {
        status: req.query.status,
        limit: Number(req.query.limit || 50),
        offset: Number(req.query.offset || 0),
      });
      return res.json({ success: true, data });
    } catch (e) {
      console.error('[INVOICE LIST MINE]', e);
      return res.status(400).json({ success: false, message: e.message });
    }
  },

  async adminList(req, res) {
    try {
      const data = await service.adminList({
        status: req.query.status,
        limit: Number(req.query.limit || 200),
        offset: Number(req.query.offset || 0),
      });
      return res.json({ success: true, data });
    } catch (e) {
      console.error('[INVOICE ADMIN LIST]', e);
      return res.status(403).json({ success: false, message: e.message });
    }
  },

  async revenueSummary(req, res) {
    try {
      const data = await service.getRevenueSummary();
      return res.json({ success: true, data });
    } catch (e) {
      console.error('[INVOICE REVENUE SUMMARY]', e);
      return res.status(403).json({ success: false, message: e.message });
    }
  },

  async pay(req, res) {
    try {
      const data = await service.markPaid(req.params.id, {
        payment_method: req.body.payment_method,
        transaction_id: req.body.transaction_id,
        amount: req.body.amount,
        paid_at: req.body.paid_at ? new Date(req.body.paid_at) : undefined,
        details: req.body.details,
      });
      return res.json({ success: true, data });
    } catch (e) {
      console.error('[INVOICE PAY]', e);
      return res.status(400).json({ success: false, message: e.message });
    }
  },

  async updateStatus(req, res) {
    try {
      const { status } = req.body;
      if (!status) return res.status(400).json({ success: false, message: 'status is required' });
      const data = await service.updateStatus(req.params.id, status);
      const poolResult = data?._poolResult ?? null;
      if (data?._poolResult) delete data._poolResult;
      return res.json({ success: true, data, poolResult });
    } catch (e) {
      console.error('[INVOICE UPDATE STATUS]', e);
      return res.status(400).json({ success: false, message: e.message });
    }
  },

  async getDetail(req, res) {
    try {
      const data = await service.getInvoiceDetail(req.params.id);
      return res.json({ success: true, data });
    } catch (e) {
      console.error('[INVOICE DETAIL]', e);
      return res.status(400).json({ success: false, message: e.message });
    }
  },

  async downloadPdf(req, res) {
    try {
      const stream = await service.getInvoicePdfStream(req.params.id, req.user);
      res.setHeader('Content-Type', 'application/pdf');
      res.setHeader('Content-Disposition', `inline; filename="invoice-${req.params.id}.pdf"`);
      stream.pipe(res);
    } catch (e) {
      console.error('[INVOICE DOWNLOAD PDF]', e);
      if (e.message?.includes('not found') || e.message?.includes('No PDF')) {
        return res.status(404).json({ success: false, message: e.message });
      }
      return res.status(400).json({ success: false, message: e.message });
    }
  },

  async sendEmailReport(req, res) {
    try {
      const { email, from, to } = req.body;
      if (!email) return res.status(400).json({ success: false, message: 'email is required' });
      const data = await service.sendEmailReport({ email, from, to });
      return res.json({ success: true, data });
    } catch (e) {
      console.error('[INVOICE EMAIL REPORT]', e);
      return res.status(400).json({ success: false, message: e.message });
    }
  },

  async adminCreate(req, res) {
    try {
      const fields = {
        buyer_name: req.body.buyer_name,
        buyer_email: req.body.buyer_email,
        buyer_street: req.body.buyer_street,
        buyer_postal_code: req.body.buyer_postal_code,
        buyer_city: req.body.buyer_city,
        buyer_country: req.body.buyer_country,
        currency: req.body.currency || 'EUR',
        total_net: req.body.total_net,
        total_tax: req.body.total_tax,
        total_gross: req.body.total_gross,
        vat_rate: req.body.vat_rate,
        status: req.body.status || 'issued',
        issued_at: req.body.issued_at,
        due_at: req.body.due_at,
      };
      if (!fields.total_gross || isNaN(Number(fields.total_gross))) {
        return res.status(400).json({ success: false, message: 'total_gross is required and must be a number' });
      }
      const pdfBuffer = req.file ? req.file.buffer : null;
      const data = await service.adminCreateManual(fields, pdfBuffer);
      return res.status(201).json({ success: true, data });
    } catch (e) {
      console.error('[INVOICE ADMIN CREATE]', e);
      return res.status(400).json({ success: false, message: e.message });
    }
  },
};
