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





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

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

      if (!properties) {
        throw new ValidationError(
          'propertiesNotFound',
        );
      }

      const updatedProperties = await PropertiesDBApi.update(
        id,
        data,
        {
          currentUser,
          transaction,
        },
      );

      await transaction.commit();
      return updatedProperties;

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

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

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

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

}


