const db = require('../db/models');
const Memoriais_descritivos_asbuiltDBApi = require('../db/api/memoriais_descritivos_asbuilt');
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 Memoriais_descritivos_asbuiltService {
  static async create(data, currentUser) {
    const transaction = await db.sequelize.transaction();
    try {
      await Memoriais_descritivos_asbuiltDBApi.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 Memoriais_descritivos_asbuiltDBApi.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 memoriais_descritivos_asbuilt =
        await Memoriais_descritivos_asbuiltDBApi.findBy(
          { id },
          { transaction },
        );

      if (!memoriais_descritivos_asbuilt) {
        throw new ValidationError('memoriais_descritivos_asbuiltNotFound');
      }

      const updatedMemoriais_descritivos_asbuilt =
        await Memoriais_descritivos_asbuiltDBApi.update(id, data, {
          currentUser,
          transaction,
        });

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

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

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

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