
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 Dynamic_pricing_rulesDBApi {
    

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

        const dynamic_pricing_rules = await db.dynamic_pricing_rules.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        rule_type: data.rule_type
        ||
        null
            ,
            
        adjustment_percent: data.adjustment_percent
        ||
        null
            ,
            
        adjustment_amount: data.adjustment_amount
        ||
        null
            ,
            
        min_occupancy_percent: data.min_occupancy_percent
        ||
        null
            ,
            
        max_occupancy_percent: data.max_occupancy_percent
        ||
        null
            ,
            
        min_days_before: data.min_days_before
        ||
        null
            ,
            
        max_days_before: data.max_days_before
        ||
        null
            ,
            
        applies_days_of_week: data.applies_days_of_week
        ||
        null
            ,
            
        active: data.active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await dynamic_pricing_rules.setHotel( data.hotel || null, {
            transaction,
        });
        
        await dynamic_pricing_rules.setRoom_type( data.room_type || null, {
            transaction,
        });
        
        await dynamic_pricing_rules.setRate_plan( data.rate_plan || null, {
            transaction,
        });
        
        await dynamic_pricing_rules.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return dynamic_pricing_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 dynamic_pricing_rulesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                rule_type: item.rule_type
            ||
            null
            ,
            
                adjustment_percent: item.adjustment_percent
            ||
            null
            ,
            
                adjustment_amount: item.adjustment_amount
            ||
            null
            ,
            
                min_occupancy_percent: item.min_occupancy_percent
            ||
            null
            ,
            
                max_occupancy_percent: item.max_occupancy_percent
            ||
            null
            ,
            
                min_days_before: item.min_days_before
            ||
            null
            ,
            
                max_days_before: item.max_days_before
            ||
            null
            ,
            
                applies_days_of_week: item.applies_days_of_week
            ||
            null
            ,
            
                active: item.active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return dynamic_pricing_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 dynamic_pricing_rules = await db.dynamic_pricing_rules.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.rule_type !== undefined) updatePayload.rule_type = data.rule_type;
        
        
        if (data.adjustment_percent !== undefined) updatePayload.adjustment_percent = data.adjustment_percent;
        
        
        if (data.adjustment_amount !== undefined) updatePayload.adjustment_amount = data.adjustment_amount;
        
        
        if (data.min_occupancy_percent !== undefined) updatePayload.min_occupancy_percent = data.min_occupancy_percent;
        
        
        if (data.max_occupancy_percent !== undefined) updatePayload.max_occupancy_percent = data.max_occupancy_percent;
        
        
        if (data.min_days_before !== undefined) updatePayload.min_days_before = data.min_days_before;
        
        
        if (data.max_days_before !== undefined) updatePayload.max_days_before = data.max_days_before;
        
        
        if (data.applies_days_of_week !== undefined) updatePayload.applies_days_of_week = data.applies_days_of_week;
        
        
        if (data.active !== undefined) updatePayload.active = data.active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.hotel !== undefined) {
            await dynamic_pricing_rules.setHotel(
              
              data.hotel,
              
              { transaction }
            );
        }
        
        if (data.room_type !== undefined) {
            await dynamic_pricing_rules.setRoom_type(
              
              data.room_type,
              
              { transaction }
            );
        }
        
        if (data.rate_plan !== undefined) {
            await dynamic_pricing_rules.setRate_plan(
              
              data.rate_plan,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await dynamic_pricing_rules.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return dynamic_pricing_rules;
    }

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

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

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


        return dynamic_pricing_rules;
    }

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

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

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

        await dynamic_pricing_rules.destroy({
            transaction
        });

        return dynamic_pricing_rules;
    }

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

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

        if (!dynamic_pricing_rules) {
            return dynamic_pricing_rules;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.hotel = await dynamic_pricing_rules.getHotel({
            transaction
        });
        
        
        output.room_type = await dynamic_pricing_rules.getRoom_type({
            transaction
        });
        
        
        output.rate_plan = await dynamic_pricing_rules.getRate_plan({
            transaction
        });
        
        
        output.organizations = await dynamic_pricing_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.hotels,
        as: 'hotel',
        
        where: filter.hotel ? {
          [Op.or]: [
            { id: { [Op.in]: filter.hotel.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.hotel.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

      {
        model: db.rate_plans,
        as: 'rate_plan',
        
        where: filter.rate_plan ? {
          [Op.or]: [
            { id: { [Op.in]: filter.rate_plan.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.rate_plan.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.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'dynamic_pricing_rules',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.applies_days_of_week) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'dynamic_pricing_rules',
                        'applies_days_of_week',
                        filter.applies_days_of_week,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.rule_type) {
                where = {
                    ...where,
                rule_type: filter.rule_type,
            };
            }
            
            if (filter.active) {
                where = {
                    ...where,
                active: filter.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.dynamic_pricing_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(
                        'dynamic_pricing_rules',
                        'name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

