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

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

        const rate_plans = await db.rate_plans.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        plan_type: data.plan_type
        ||
        null
            ,
            
        refundable: data.refundable
        ||
        false
        
            ,
            
        min_nights: data.min_nights
        ||
        null
            ,
            
        max_nights: data.max_nights
        ||
        null
            ,
            
        deposit_percent: data.deposit_percent
        ||
        null
            ,
            
        cancellation_policy: data.cancellation_policy
        ||
        null
            ,
            
        active: data.active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await rate_plans.setHotel( data.hotel || null, {
            transaction,
        });
        
        await rate_plans.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return rate_plans;
    }
    

    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 rate_plansData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                plan_type: item.plan_type
            ||
            null
            ,
            
                refundable: item.refundable
            ||
            false
        
            ,
            
                min_nights: item.min_nights
            ||
            null
            ,
            
                max_nights: item.max_nights
            ||
            null
            ,
            
                deposit_percent: item.deposit_percent
            ||
            null
            ,
            
                cancellation_policy: item.cancellation_policy
            ||
            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 rate_plans = await db.rate_plans.bulkCreate(rate_plansData, { transaction });

        // For each item created, replace relation files
        

        return rate_plans;
    }

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.plan_type !== undefined) updatePayload.plan_type = data.plan_type;
        
        
        if (data.refundable !== undefined) updatePayload.refundable = data.refundable;
        
        
        if (data.min_nights !== undefined) updatePayload.min_nights = data.min_nights;
        
        
        if (data.max_nights !== undefined) updatePayload.max_nights = data.max_nights;
        
        
        if (data.deposit_percent !== undefined) updatePayload.deposit_percent = data.deposit_percent;
        
        
        if (data.cancellation_policy !== undefined) updatePayload.cancellation_policy = data.cancellation_policy;
        
        
        if (data.active !== undefined) updatePayload.active = data.active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.hotel !== undefined) {
            await rate_plans.setHotel(
              
              data.hotel,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await rate_plans.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return rate_plans;
    }

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

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

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


        return rate_plans;
    }

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

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

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

        await rate_plans.destroy({
            transaction
        });

        return rate_plans;
    }

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

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

        if (!rate_plans) {
            return rate_plans;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.seasonal_rates_rate_plan = await rate_plans.getSeasonal_rates_rate_plan({
            transaction
        });
        
        
        output.dynamic_pricing_rules_rate_plan = await rate_plans.getDynamic_pricing_rules_rate_plan({
            transaction
        });
        
        
        
        
        output.reservations_rate_plan = await rate_plans.getReservations_rate_plan({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.hotel = await rate_plans.getHotel({
            transaction
        });
        
        
        output.organizations = await rate_plans.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.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'rate_plans',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.cancellation_policy) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'rate_plans',
                        'cancellation_policy',
                        filter.cancellation_policy,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

            
            if (filter.plan_type) {
                where = {
                    ...where,
                plan_type: filter.plan_type,
            };
            }
            
            if (filter.refundable) {
                where = {
                    ...where,
                refundable: filter.refundable,
            };
            }
            
            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.rate_plans.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(
                        'rate_plans',
                        'name',
                        query,
                    ),
                ],
            };
        }

        const records = await db.rate_plans.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,
        }));
    }

    
};

