const fs = require('fs')
const readXlsxFile = require('read-excel-file/node')

const guaranteeSerialsPath = './static/uploads/serials'
const productSerialsPath = './static/uploads/serials_products'

const serialChecker =  (serial, type = 'guaranteeSerial', g = 1) => {
  return new Promise(async (resolve, reject) => {
    let exelsPath;
    if (type === 'guaranteeSerial') exelsPath = guaranteeSerialsPath + `/${g}`;
    if (type === 'orginality') exelsPath = productSerialsPath + `/${g}`;

    const newTxt = serial.toLowerCase().split("-")
    let lowerSerial = ""
    for(const item of newTxt){
    
      lowerSerial += item
        
    }
    try {
      const serialFiles = await fs.readdirSync(exelsPath);
      if ((serialFiles?.length) <= 0) {
        // eslint-disable-next-line prefer-promise-reject-errors
        reject("این کد در سامانه موجود نیست")
      }
      serialFiles.forEach(async (file, i) => {
        const exelFile = await readXlsxFile(`${exelsPath}/${file}`);

        for (const row of exelFile) {
          
            // eslint-disable-next-line eqeqeq
            if ((row[1].toString()).toLowerCase() == lowerSerial) {
              resolve(row[2]);
              return; // Serial found, exit loop
            }
          
        }
        if ((serialFiles.length - 1) <= i) {
          // eslint-disable-next-line prefer-promise-reject-errors
          reject("این کد در سامانه موجود نیست")
        }
      })

    } catch (e) {
      console.log(e);
      reject(e);
    }
  });
};

module.exports.serialChecker = serialChecker
