const { db } = require("../db/db-connect");
const logger = require("../utils/logger");
const numeral = require("numeral");

require("numeral/locales/fr");
numeral.locale("fr");

async function getRecordIdFromFieldValue(collection, field, value) {
  try {
    const resultList = await db.records.getList(collection, 1, 1, {
      filter: `${field} = '${value}'`,
    });

    if (resultList.totalItems > 0) {
      return resultList.items[0].id;
    } else {
      return null;
    }
  } catch (error) {
    logger.log("error", error);

    return null;
  }
}

async function fetchInfoByCriteria(collection, criteria) {
  try {
    const resultList = await db.records.getList(collection, 1, 1, criteria);

    if (resultList.totalItems > 0) {
      return resultList.items[0];
    }
  } catch (error) {
    logger.log("error", error);
  }

  return null;
}

async function updateRecordFromData(collection, recordID, data) {
  try {
    const record = await db.records.update(collection, recordID, data);

    return record;
  } catch (error) {
    logger.log("error", error);
  }

  return null;
}

function customFormatNumber(number, decimal, taux = false) {
  if (Number.isInteger(number)) {
    if (decimal == true) {
      return numeral(number).format("0,0.00");
    } else {
      return numeral(number).format("0,0");
    }
  } else {
    if (taux == true) {
      return numeral(number).format("0,0.000");
    } else {
      return numeral(number).format("0,0.00");
    }
  }
}

function cleanDoubleSpaces(inputString) {
  return inputString.replace(/\s{2,}/g, " ");
}

module.exports = {
  getRecordIdFromFieldValue,
  fetchInfoByCriteria,
  updateRecordFromData,
  cleanDoubleSpaces,
  customFormatNumber,
};
