const { stringify } = require('csv-stringify/sync');
const reportModel = require('../models/reportModel');

function defaultDates(query) {
  const now = new Date();
  const first = new Date(now.getFullYear(), now.getMonth(), 1).toISOString().slice(0, 10);
  const today = now.toISOString().slice(0, 10);
  return { from: query.from || first, to: query.to || today };
}

async function index(req, res) {
  const dates = defaultDates(req.query);
  const invoiceRows = await reportModel.invoiceReport(dates.from, dates.to);
  const hsnRows = await reportModel.hsnSummary(dates.from, dates.to);
  res.render('reports/index', { title: 'Reports', dates, invoiceRows, hsnRows });
}

async function download(req, res) {
  const dates = defaultDates(req.query);
  const type = req.params.type;
  let rows;
  if (type === 'gst') rows = await reportModel.gstSummary(dates.from, dates.to);
  else if (type === 'hsn') rows = await reportModel.hsnSummary(dates.from, dates.to);
  else rows = await reportModel.invoiceReport(dates.from, dates.to);
  const csv = stringify(rows, { header: true });
  res.setHeader('Content-Type', 'text/csv');
  res.setHeader('Content-Disposition', `attachment; filename="${type}-report-${dates.from}-to-${dates.to}.csv"`);
  res.send(csv);
}

module.exports = { index, download };
