const db = require('../db/models');
const Payroll_line_itemsDBApi = require('../db/api/payroll_line_items');
const processFile = require("../middlewares/upload");
const ValidationError = require('./notifications/errors/validation');
const csv = require('csv-parser');
const axios = require('axios');
const config = require('../config');
const stream = require('stream');





module.exports = class Payroll_line_itemsService {
  static async create(data, currentUser) {
    const transaction = await db.sequelize.transaction();
    try {
      if (data.job_logId && data.gross_pay) {
        const jobLog = await db.job_logs.findByPk(data.job_logId, { transaction });
        if (jobLog && jobLog.workersCompClassId) {
          const compClass = await db.workers_comp_classes.findByPk(jobLog.workersCompClassId, { transaction });
          if (compClass && compClass.percentage) {
            data.workers_comp_amount = (Number(data.gross_pay || 0) * Number(compClass.percentage || 0)) / 100;
          }
        }
      }
      await Payroll_line_itemsDBApi.create(
        data,
        {
          currentUser,
          transaction,
        },
      );

      await transaction.commit();
    } catch (error) {
      await transaction.rollback();
      throw error;
    }
  };

  static async bulkImport(req, res, sendInvitationEmails = true, host) {
    const transaction = await db.sequelize.transaction();

    try {
      await processFile(req, res);
      const bufferStream = new stream.PassThrough();
      const results = [];

      await bufferStream.end(Buffer.from(req.file.buffer, "utf-8")); // convert Buffer to Stream

      await new Promise((resolve, reject) => {
        bufferStream
          .pipe(csv())
          .on('data', (data) => results.push(data))
          .on('end', async () => {
            console.log('CSV results', results);
            resolve();
          })
          .on('error', (error) => reject(error));
      })

      await Payroll_line_itemsDBApi.bulkImport(results, {
          transaction,
          ignoreDuplicates: true,
          validate: true,
          currentUser: req.currentUser
      });

      await transaction.commit();
    } catch (error) {
      await transaction.rollback();
      throw error;
    }
  }

  static async update(data, id, currentUser) {
    const transaction = await db.sequelize.transaction();
    try {
      let payroll_line_items = await Payroll_line_itemsDBApi.findBy(
        {id},
        {transaction},
      );

      if (!payroll_line_items) {
        throw new ValidationError(
          'payroll_line_itemsNotFound',
        );
      }

      const updatedPayroll_line_items = await Payroll_line_itemsDBApi.update(
        id,
        data,
        {
          currentUser,
          transaction,
        },
      );

      await transaction.commit();
      return updatedPayroll_line_items;

    } catch (error) {
      await transaction.rollback();
      throw error;
    }
  };

  static async deleteByIds(ids, currentUser) {
    const transaction = await db.sequelize.transaction();

    try {
      await Payroll_line_itemsDBApi.deleteByIds(ids, {
        currentUser,
        transaction,
      });

      await transaction.commit();
    } catch (error) {
      await transaction.rollback();
      throw error;
    }
  }

  static async remove(id, currentUser) {
    const transaction = await db.sequelize.transaction();

    try {
      await Payroll_line_itemsDBApi.remove(
        id,
        {
          currentUser,
          transaction,
        },
      );

      await transaction.commit();
    } catch (error) {
      await transaction.rollback();
      throw error;
    }
  }

  
};


