const fs = require('fs-extra');
const jsonToCsv = require('./json-to-csv');

function writeItem(data) {
  if (!fs.existsSync(`mock-api/resources/${data.id}`)) {
    fs.mkdirSync(`mock-api/resources/${data.id}`);
  }

  const promises = [];
  promises.push(
    fs.writeFile(`mock-api/resources/${data.id}/contents.csv`, `${jsonToCsv(data.content.data)}\n`),
  );

  const item = { ...data };
  item.field_definition = {};
  item.webapp_manifest = {};
  item.content.data = {};

  promises.push(
    fs.writeFile(`mock-api/resources/${data.id}/item.json`, `${JSON.stringify(item, null, 2)}\n`),
  );
  promises.push(
    fs.writeFile(
      `mock-api/resources/${data.id}/webapp-manifest.json`,
      `${JSON.stringify(data.webapp_manifest, null, 2)}\n`,
    ),
  );
  promises.push(
    fs.writeFile(
      `mock-api/resources/${data.id}/field-definitions.json`,
      `${JSON.stringify(data.field_definition, null, 2)}\n`,
    ),
  );

  return Promise.all(promises);
}

module.exports = writeItem;
