const path = require('path');
const readXlsxFile = require('read-excel-file/node');
const writeXlsxFile = require('write-excel-file/node');
const Papa = require('papaparse');
const { XMLBuilder, XMLParser } = require('fast-xml-parser');
const { now } = require('../db');
const { assetExportRows } = require('./assets');

async function rowsFromImport(format, buffer) {
  const text = buffer.toString('utf8');
  if (format === 'json') {
    const parsed = JSON.parse(text);
    return Array.isArray(parsed) ? parsed : parsed.assets || [];
  }
  if (format === 'xml') {
    const parsed = new XMLParser({ ignoreAttributes: false }).parse(text);
    const assets = parsed.assets?.asset || parsed.DepreCore?.assets?.asset || [];
    return Array.isArray(assets) ? assets : [assets];
  }
  if (format === 'xlsx' || format === 'xls') {
    const rows = await readXlsxFile(buffer);
    const headers = (rows.shift() || []).map((header) => String(header || '').trim());
    return rows.map((row) => Object.fromEntries(headers.map((header, index) => [header, row[index]])));
  }
  return Papa.parse(text, { header: true, skipEmptyLines: true }).data;
}

async function assetExport(format, companyId) {
  const rows = assetExportRows(companyId);
  if (format === 'csv') {
    return {
      contentType: 'text/csv',
      filename: 'deprecore-assets.csv',
      body: Papa.unparse(rows)
    };
  }
  if (format === 'xlsx') {
    const columns = Object.keys(rows[0] || {
      asset_id: '',
      description: '',
      category: '',
      status: '',
      acquisition_cost: '',
      in_service_date: ''
    });
    const sheetData = [
      columns.map((column) => ({ value: column, fontWeight: 'bold' })),
      ...rows.map((row) => columns.map((column) => ({
        value: typeof row[column] === 'object' && row[column] !== null ? JSON.stringify(row[column]) : row[column]
      })))
    ];
    return {
      contentType: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
      filename: 'deprecore-assets.xlsx',
      body: await writeXlsxFile(sheetData).toBuffer()
    };
  }
  if (format === 'xml') {
    return {
      contentType: 'application/xml',
      filename: 'deprecore-assets.xml',
      body: new XMLBuilder({ format: true }).build({ assets: { asset: rows } })
    };
  }
  return {
    contentType: 'application/json',
    filename: 'deprecore-assets.json',
    body: JSON.stringify({ exportedAt: now(), assets: rows })
  };
}

function extensionForUpload(fileName) {
  return path.extname(fileName).replace('.', '').toLowerCase() || 'csv';
}

module.exports = {
  assetExport,
  extensionForUpload,
  rowsFromImport
};
