
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
            ,
            
        code: data.code
        ||
        null
            ,
            
        pricing_model: data.pricing_model
        ||
        null
            ,
            
        cancellation_policy_type: data.cancellation_policy_type
        ||
        null
            ,
            
        cancellation_policy_text: data.cancellation_policy_text
        ||
        null
            ,
            
        min_stay_nights: data.min_stay_nights
        ||
        null
            ,
            
        max_stay_nights: data.max_stay_nights
        ||
        null
            ,
            
        release_days: data.release_days
        ||
        null
            ,
            
        is_breakfast_included: data.is_breakfast_included
        ||
        false
        
            ,
            
        is_refundable: data.is_refundable
        ||
        false
        
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await rate_plans.setHotel( data.hotel || 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
            ,
            
                code: item.code
            ||
            null
            ,
            
                pricing_model: item.pricing_model
            ||
            null
            ,
            
                cancellation_policy_type: item.cancellation_policy_type
            ||
            null
            ,
            
                cancellation_policy_text: item.cancellation_policy_text
            ||
            null
            ,
            
                min_stay_nights: item.min_stay_nights
            ||
            null
            ,
            
                max_stay_nights: item.max_stay_nights
            ||
            null
            ,
            
                release_days: item.release_days
            ||
            null
            ,
            
                is_breakfast_included: item.is_breakfast_included
            ||
            false
        
            ,
            
                is_refundable: item.is_refundable
            ||
            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 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 rate_plans = await db.rate_plans.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.code !== undefined) updatePayload.code = data.code;
        
        
        if (data.pricing_model !== undefined) updatePayload.pricing_model = data.pricing_model;
        
        
        if (data.cancellation_policy_type !== undefined) updatePayload.cancellation_policy_type = data.cancellation_policy_type;
        
        
        if (data.cancellation_policy_text !== undefined) updatePayload.cancellation_policy_text = data.cancellation_policy_text;
        
        
        if (data.min_stay_nights !== undefined) updatePayload.min_stay_nights = data.min_stay_nights;
        
        
        if (data.max_stay_nights !== undefined) updatePayload.max_stay_nights = data.max_stay_nights;
        
        
        if (data.release_days !== undefined) updatePayload.release_days = data.release_days;
        
        
        if (data.is_breakfast_included !== undefined) updatePayload.is_breakfast_included = data.is_breakfast_included;
        
        
        if (data.is_refundable !== undefined) updatePayload.is_refundable = data.is_refundable;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.hotel !== undefined) {
            await rate_plans.setHotel(
              
              data.hotel,
              
              { 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.bookings_rate_plan = await rate_plans.getBookings_rate_plan({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.hotel = await rate_plans.getHotel({
            transaction
        });
        
        

        return output;
    }

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

        

        

        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}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

        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.code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'rate_plans',
                        'code',
                        filter.code,
                    ),
                };
            }
            
            if (filter.cancellation_policy_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'rate_plans',
                        'cancellation_policy_text',
                        filter.cancellation_policy_text,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

            
            if (filter.pricing_model) {
                where = {
                    ...where,
                pricing_model: filter.pricing_model,
            };
            }
            
            if (filter.cancellation_policy_type) {
                where = {
                    ...where,
                cancellation_policy_type: filter.cancellation_policy_type,
            };
            }
            
            if (filter.is_breakfast_included) {
                where = {
                    ...where,
                is_breakfast_included: filter.is_breakfast_included,
            };
            }
            
            if (filter.is_refundable) {
                where = {
                    ...where,
                is_refundable: filter.is_refundable,
            };
            }
            
            if (filter.is_active) {
                where = {
                    ...where,
                is_active: filter.is_active,
            };
            }
            


      



            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,
                        },
                    };
                }
            }
        }
        

        

        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, ) {
        let where = {};
        
        

        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,
        }));
    }

    
};

