const { parse } = require('json2csv');

const getTemplateForProperties = (currentUser) => {
  const globalAccess = Boolean(currentUser?.app_role?.globalAccess);
  const columns = globalAccess
    ? ['tenant', 'organization', 'name', 'code', 'address', 'city', 'country', 'timezone', 'description', 'is_active']
    : ['name', 'code', 'address', 'city', 'country', 'timezone', 'description', 'is_active'];

  return {
    columns,
    requiredColumns: globalAccess ? ['organization'] : [],
    fileName: 'properties-import-template.csv',
  };
};

const getTemplateForUnitTypes = () => ({
  columns: [
    'property',
    'name',
    'code',
    'description',
    'max_occupancy',
    'bedrooms',
    'bathrooms',
    'minimum_stay_nights',
    'size_sqm',
    'base_nightly_rate',
    'base_monthly_rate',
  ],
  requiredColumns: ['property'],
  fileName: 'unit-types-import-template.csv',
});

const getTemplateForUnits = () => ({
  columns: [
    'property',
    'unit_type',
    'unit_number',
    'floor',
    'status',
    'max_occupancy_override',
    'notes',
  ],
  requiredColumns: ['property', 'unit_type'],
  fileName: 'units-import-template.csv',
});

const TEMPLATE_FACTORIES = {
  properties: getTemplateForProperties,
  unit_types: getTemplateForUnitTypes,
  units: getTemplateForUnits,
};

const getInventoryImportTemplate = (entity, currentUser) => {
  const factory = TEMPLATE_FACTORIES[entity];

  if (!factory) {
    throw new Error(`Unknown inventory import template entity: ${entity}`);
  }

  return factory(currentUser);
};

const buildInventoryImportTemplateCsv = (entity, currentUser) => {
  const template = getInventoryImportTemplate(entity, currentUser);
  return parse([], { fields: template.columns });
};

module.exports = {
  buildInventoryImportTemplateCsv,
  getInventoryImportTemplate,
};
