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

module.exports = class Verification_submissionsService {
  static async create(data, currentUser) {
    const transaction = await db.sequelize.transaction();
    try {
      // Ownership check for Verified Business Owner
      if (currentUser.app_role?.name === 'Verified Business Owner') {
          const businessId = data.business || currentUser.businessId;
          const business = await db.businesses.findByPk(businessId, { transaction });
          if (!business || (business.owner_userId !== currentUser.id && business.id !== currentUser.businessId)) {
              throw new ForbiddenError('forbidden');
          }
          data.business = business.id;
      }

      const submission = await Verification_submissionsDBApi.create(
        data,
        {
          currentUser,
          transaction,
        },
      );

      await transaction.commit();
      return submission;
    } 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")); 

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

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

      if (!verification_submissions) {
        throw new ValidationError(
          'verification_submissionsNotFound',
        );
      }

      // Ownership check for Verified Business Owner
      if (currentUser.app_role?.name === 'Verified Business Owner') {
          const businessId = verification_submissions.business?.id;
          const business = await db.businesses.findByPk(businessId, { transaction });
          if (!business || (business.owner_userId !== currentUser.id && business.id !== currentUser.businessId)) {
              throw new ForbiddenError('forbidden');
          }
      }

      const updatedVerification_submissions = await Verification_submissionsDBApi.update(
        id,
        data,
        {
          currentUser,
          transaction,
        },
      );

      await transaction.commit();
      return updatedVerification_submissions;

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

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

    try {
      // Ownership check for Verified Business Owner
      if (currentUser.app_role?.name === 'Verified Business Owner') {
          const records = await db.verification_submissions.findAll({ 
              where: { id: { [db.Sequelize.Op.in]: ids } },
              include: [{ model: db.businesses, as: 'business' }],
              transaction 
          });
          for (const record of records) {
              if (record.business?.owner_userId !== currentUser.id && record.business?.id !== currentUser.businessId) {
                  throw new ForbiddenError('forbidden');
              }
          }
      }

      await Verification_submissionsDBApi.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 {
      const record = await db.verification_submissions.findByPk(id, {
          include: [{ model: db.businesses, as: 'business' }],
          transaction
      });
      if (!record) throw new ValidationError('verification_submissionsNotFound');

      if (currentUser.app_role?.name === 'Verified Business Owner') {
          if (record.business?.owner_userId !== currentUser.id && record.business?.id !== currentUser.businessId) {
              throw new ForbiddenError('forbidden');
          }
      }

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

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

  
};