const { buildTenantQuery } = require('./accessControl');

const flattenValue = (value) => {
  if (value === null || value === undefined) return '';
  if (typeof value === 'object') {
    if (value.name) return value.name;
    if (value.code) return value.code;
    if (value.amount !== undefined) return `${value.currency || ''} ${value.amount}`.trim();
    return JSON.stringify(value);
  }
  return String(value);
};

const toCsv = (rows = []) => {
  if (!rows.length) return '';
  const headers = [...new Set(rows.flatMap((row) => Object.keys(row)))];
  const escape = (value) => `"${String(value || '').replace(/"/g, '""')}"`;
  const lines = [
    headers.map(escape).join(','),
    ...rows.map((row) => headers.map((header) => escape(flattenValue(row[header]))).join(',')),
  ];
  return lines.join('\n');
};

const exportModelCsv = async ({ Model, req, res, query = {} }) => {
  const { sortBy = 'created', sortValue = -1, filter, equal, limit = 500 } = query;
  const filterCondition = filter && equal !== undefined ? { [filter]: equal } : {};
  const rows = await Model.find({
    removed: false,
    ...buildTenantQuery(Model, req),
    ...filterCondition,
  })
    .limit(Number(limit))
    .sort({ [sortBy]: sortValue })
    .lean();

  const csv = toCsv(rows);
  res.setHeader('Content-Type', 'text/csv; charset=utf-8');
  res.setHeader('Content-Disposition', `attachment; filename="${Model.modelName.toLowerCase()}-export.csv"`);
  return res.status(200).send(csv);
};

module.exports = { toCsv, exportModelCsv };
