const db = require('../db/models');
const Service_pricesDBApi = require('../db/api/service_prices');
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 Service_pricesService {
  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) {
              throw new ForbiddenError('forbidden');
          }
          data.business = business.id;
      }

      const service_price = await Service_pricesDBApi.create(
        data,
        {
          currentUser,
          transaction,
        },
      );

      await transaction.commit();
      return service_price;
    } 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 Service_pricesDBApi.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 service_prices = await Service_pricesDBApi.findBy(
        {id},
        {transaction},
      );

      if (!service_prices) {
        throw new ValidationError(
          'service_pricesNotFound',
        );
      }

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

      const updatedService_prices = await Service_pricesDBApi.update(
        id,
        data,
        {
          currentUser,
          transaction,
        },
      );

      await transaction.commit();
      return updatedService_prices;

    } 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.service_prices.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 Service_pricesDBApi.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.service_prices.findByPk(id, {
          include: [{ model: db.businesses, as: 'business' }],
          transaction
      });
      if (!record) throw new ValidationError('service_pricesNotFound');

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

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

  
};