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

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

        const seasonal_rates = await db.seasonal_rates.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        start_at: data.start_at
        ||
        null
            ,
            
        end_at: data.end_at
        ||
        null
            ,
            
        price_amount: data.price_amount
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        min_stay_nights: data.min_stay_nights
        ||
        null
            ,
            
        max_stay_nights: data.max_stay_nights
        ||
        null
            ,
            
        closed_to_arrival: data.closed_to_arrival
        ||
        false
        
            ,
            
        closed_to_departure: data.closed_to_departure
        ||
        false
        
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await seasonal_rates.setRoom_type( data.room_type || null, {
            transaction,
        });
        
        await seasonal_rates.setRate_plan( data.rate_plan || null, {
            transaction,
        });
        

        

        

        return seasonal_rates;
    }
    

    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 seasonal_ratesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                start_at: item.start_at
            ||
            null
            ,
            
                end_at: item.end_at
            ||
            null
            ,
            
                price_amount: item.price_amount
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                min_stay_nights: item.min_stay_nights
            ||
            null
            ,
            
                max_stay_nights: item.max_stay_nights
            ||
            null
            ,
            
                closed_to_arrival: item.closed_to_arrival
            ||
            false
        
            ,
            
                closed_to_departure: item.closed_to_departure
            ||
            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 seasonal_rates = await db.seasonal_rates.bulkCreate(seasonal_ratesData, { transaction });

        // For each item created, replace relation files
        

        return seasonal_rates;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.start_at !== undefined) updatePayload.start_at = data.start_at;
        
        
        if (data.end_at !== undefined) updatePayload.end_at = data.end_at;
        
        
        if (data.price_amount !== undefined) updatePayload.price_amount = data.price_amount;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        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.closed_to_arrival !== undefined) updatePayload.closed_to_arrival = data.closed_to_arrival;
        
        
        if (data.closed_to_departure !== undefined) updatePayload.closed_to_departure = data.closed_to_departure;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.room_type !== undefined) {
            await seasonal_rates.setRoom_type(
              
              data.room_type,
              
              { transaction }
            );
        }
        
        if (data.rate_plan !== undefined) {
            await seasonal_rates.setRate_plan(
              
              data.rate_plan,
              
              { transaction }
            );
        }
        

        
        

        

        return seasonal_rates;
    }

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

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

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


        return seasonal_rates;
    }

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

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

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

        await seasonal_rates.destroy({
            transaction
        });

        return seasonal_rates;
    }

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

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

        if (!seasonal_rates) {
            return seasonal_rates;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.room_type = await seasonal_rates.getRoom_type({
            transaction
        });
        
        
        output.rate_plan = await seasonal_rates.getRate_plan({
            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.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}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

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

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            start_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    end_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    end_at: {
                    ...where.end_at,
                            [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.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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

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

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

    
};

