const db = require('../db/models');
const UnitsDBApi = require('../db/api/units');
const ValidationError = require('./notifications/errors/validation');
const { parseCsvImportFile } = require('./importer');
const { getInventoryImportTemplate } = require('./inventoryImportTemplates');





module.exports = class UnitsService {
  static async create(data, currentUser) {
    const transaction = await db.sequelize.transaction();
    try {
      await UnitsDBApi.create(
        data,
        {
          currentUser,
          transaction,
        },
      );

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

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

    try {
      const results = await parseCsvImportFile(
        req,
        res,
        getInventoryImportTemplate('units', req.currentUser),
      );

      await UnitsDBApi.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 units = await UnitsDBApi.findBy(
        {id},
        {transaction},
      );

      if (!units) {
        throw new ValidationError(
          'unitsNotFound',
        );
      }

      const updatedUnits = await UnitsDBApi.update(
        id,
        data,
        {
          currentUser,
          transaction,
        },
      );

      await transaction.commit();
      return updatedUnits;

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

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

    try {
      await UnitsDBApi.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 UnitsDBApi.remove(
        id,
        {
          currentUser,
          transaction,
        },
      );

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

}


