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





module.exports = class Unit_typesService {
  static async create(data, currentUser) {
    const transaction = await db.sequelize.transaction();
    try {
      await Unit_typesDBApi.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('unit_types', req.currentUser),
      );

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

      if (!unit_types) {
        throw new ValidationError(
          'unit_typesNotFound',
        );
      }

      const updatedUnit_types = await Unit_typesDBApi.update(
        id,
        data,
        {
          currentUser,
          transaction,
        },
      );

      await transaction.commit();
      return updatedUnit_types;

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

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

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

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

}


