import saleService from '../services/saleService.js';
import { getSettings } from '../repositories/settingsRepository.js';
import { generateInvoicePDF } from '../utils/pdfGenerator.js';

export const getAll = async (req, res, next) => {
  try {
    const result = await saleService.getAllSales(req.query, req.user);
    res.json({ success: true, data: result });
  } catch (error) {
    next(error);
  }
};

export const getById = async (req, res, next) => {
  try {
    const sale = await saleService.getSaleById(req.params.id);
    res.json({ success: true, data: sale });
  } catch (error) {
    next(error);
  }
};

export const create = async (req, res, next) => {
  try {
    const sale = await saleService.createSale(req.body, req);
    res.status(201).json({ success: true, message: 'Sale completed', data: sale });
  } catch (error) {
    next(error);
  }
};

export const getInvoice = async (req, res, next) => {
  try {
    const sale = await saleService.getSaleById(req.params.id);
    const settings = await getSettings();

    res.setHeader('Content-Type', 'application/pdf');
    res.setHeader('Content-Disposition', `attachment; filename=${sale.billNumber}.pdf`);

    generateInvoicePDF(sale, settings, res);
  } catch (error) {
    next(error);
  }
};
