
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');



const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class Price_rulesDBApi {
    

    
    static async create(data, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        const price_rules = await db.price_rules.create(
            {
                id: data.id || undefined,
        
        min_participants: data.min_participants
        ||
        null
            ,
            
        max_participants: data.max_participants
        ||
        null
            ,
            
        price_amount: data.price_amount
        ||
        null
            ,
            
        is_split_payment_allowed: data.is_split_payment_allowed
        ||
        false
        
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await price_rules.setPrice_list( data.price_list || null, {
            transaction,
        });
        
        await price_rules.setService_type( data.service_type || null, {
            transaction,
        });
        
        await price_rules.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return price_rules;
    }
    

    static async bulkImport(data, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        // Prepare data - wrapping individual data transformations in a map() method
        const price_rulesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                min_participants: item.min_participants
            ||
            null
            ,
            
                max_participants: item.max_participants
            ||
            null
            ,
            
                price_amount: item.price_amount
            ||
            null
            ,
            
                is_split_payment_allowed: item.is_split_payment_allowed
            ||
            false
        
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

        // Bulk create items
        const price_rules = await db.price_rules.bulkCreate(price_rulesData, { transaction });

        // For each item created, replace relation files
        

        return price_rules;
    }

    static async update(id, data,  options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;
        const globalAccess = currentUser.app_role?.globalAccess;

        const price_rules = await db.price_rules.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.min_participants !== undefined) updatePayload.min_participants = data.min_participants;
        
        
        if (data.max_participants !== undefined) updatePayload.max_participants = data.max_participants;
        
        
        if (data.price_amount !== undefined) updatePayload.price_amount = data.price_amount;
        
        
        if (data.is_split_payment_allowed !== undefined) updatePayload.is_split_payment_allowed = data.is_split_payment_allowed;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

        await price_rules.update(updatePayload, {transaction});

        
        
        if (data.price_list !== undefined) {
            await price_rules.setPrice_list(
              
              data.price_list,
              
              { transaction }
            );
        }
        
        if (data.service_type !== undefined) {
            await price_rules.setService_type(
              
              data.service_type,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await price_rules.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return price_rules;
    }

    static async deleteByIds(ids, options) {
        const currentUser = (options && options.currentUser) || { id: null };
        const transaction = (options && options.transaction) || undefined;

        const price_rules = await db.price_rules.findAll({
            where: {
                id: {
                    [Op.in]: ids,
                },
            },
            transaction,
        });

        await db.sequelize.transaction(async (transaction) => {
            for (const record of price_rules) {
                await record.update(
                    {deletedBy: currentUser.id},
                    {transaction}
                );
            }
            for (const record of price_rules) {
                await record.destroy({transaction});
            }
        });


        return price_rules;
    }

    static async remove(id, options) {
        const currentUser = (options && options.currentUser) || {id: null};
        const transaction = (options && options.transaction) || undefined;

        const price_rules = await db.price_rules.findByPk(id, options);

        await price_rules.update({
            deletedBy: currentUser.id
        }, {
            transaction,
        });

        await price_rules.destroy({
            transaction
        });

        return price_rules;
    }

    static async findBy(where, options) {
        const transaction = (options && options.transaction) || undefined;

        const price_rules = await db.price_rules.findOne(
            { where },
            { transaction },
        );

        if (!price_rules) {
            return price_rules;
        }

        const output = price_rules.get({plain: true});

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.price_list = await price_rules.getPrice_list({
            transaction
        });
        
        
        output.service_type = await price_rules.getService_type({
            transaction
        });
        
        
        output.organizations = await price_rules.getOrganizations({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

      {
        model: db.price_lists,
        as: 'price_list',
        
        where: filter.price_list ? {
          [Op.or]: [
            { id: { [Op.in]: filter.price_list.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.price_list.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.service_types,
        as: 'service_type',
        
        where: filter.service_type ? {
          [Op.or]: [
            { id: { [Op.in]: filter.service_type.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.service_type.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.organizations,
        as: 'organizations',
        
      },



    ];

        if (filter) {
            if (filter.id) {
                where = {
                    ...where,
                    ['id']: Utils.uuid(filter.id),
                };
            }

            

            
            

            
            if (filter.min_participantsRange) {
                const [start, end] = filter.min_participantsRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    min_participants: {
                    ...where.min_participants,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    min_participants: {
                    ...where.min_participants,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.max_participantsRange) {
                const [start, end] = filter.max_participantsRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    max_participants: {
                    ...where.max_participants,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    max_participants: {
                    ...where.max_participants,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.price_amountRange) {
                const [start, end] = filter.price_amountRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                    price_amount: {
                    ...where.price_amount,
                            [Op.gte]: start,
                    },
                };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    price_amount: {
                    ...where.price_amount,
                            [Op.lte]: end,
                    },
                };
                }
            }
            

            if (filter.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            
            if (filter.is_split_payment_allowed) {
                where = {
                    ...where,
                is_split_payment_allowed: filter.is_split_payment_allowed,
            };
            }
            
            if (filter.is_active) {
                where = {
                    ...where,
                is_active: filter.is_active,
            };
            }
            


      

      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[Op.or]: listItems}
        };
      }
      



            if (filter.createdAtRange) {
                const [start, end] = filter.createdAtRange;

                if (start !== undefined && start !== null && start !== '') {
                    where = {
                        ...where,
                        ['createdAt']: {
                            ...where.createdAt,
                            [Op.gte]: start,
                        },
                    };
                }

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                        ['createdAt']: {
                            ...where.createdAt,
                            [Op.lte]: end,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.organizationsId;
        }
        

        const queryOptions = {
            where,
            include,
            distinct: true,
            order: filter.field && filter.sort
                ? [[filter.field, filter.sort]]
                : [['createdAt', 'desc']],
            transaction: options?.transaction,
            logging: console.log
        };

        if (!options?.countOnly) {
            queryOptions.limit = limit ? Number(limit) : undefined;
            queryOptions.offset = offset ? Number(offset) : undefined;
        }

        try {
            const { rows, count } = await db.price_rules.findAndCountAll(queryOptions);

            return {
                rows: options?.countOnly ? [] : rows,
                count: count
            };
        } catch (error) {
            console.error('Error executing query:', error);
            throw error;
        }
    }

    static async findAllAutocomplete(query, limit, offset,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'price_rules',
                        'price_amount',
                        query,
                    ),
                ],
            };
        }

        const records = await db.price_rules.findAll({
            attributes: [ 'id', 'price_amount' ],
            where,
            limit: limit ? Number(limit) : undefined,
            offset: offset ? Number(offset) : undefined,
            orderBy: [['price_amount', 'ASC']],
        });

        return records.map((record) => ({
            id: record.id,
            label: record.price_amount,
        }));
    }

    
};

