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

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

        const negotiated_rates = await db.negotiated_rates.create(
            {
                id: data.id || undefined,
        
        rate_type: data.rate_type
        ||
        null
            ,
            
        rate_amount: data.rate_amount
        ||
        null
            ,
            
        valid_from: data.valid_from
        ||
        null
            ,
            
        valid_until: data.valid_until
        ||
        null
            ,
            
        minimum_stay_nights: data.minimum_stay_nights
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await negotiated_rates.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await negotiated_rates.setProperty( data.property || null, {
            transaction,
        });
        
        await negotiated_rates.setUnit_type( data.unit_type || null, {
            transaction,
        });
        

        

        

        return negotiated_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 negotiated_ratesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                rate_type: item.rate_type
            ||
            null
            ,
            
                rate_amount: item.rate_amount
            ||
            null
            ,
            
                valid_from: item.valid_from
            ||
            null
            ,
            
                valid_until: item.valid_until
            ||
            null
            ,
            
                minimum_stay_nights: item.minimum_stay_nights
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return negotiated_rates;
    }

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


        

        const updatePayload = {};
        
        if (data.rate_type !== undefined) updatePayload.rate_type = data.rate_type;
        
        
        if (data.rate_amount !== undefined) updatePayload.rate_amount = data.rate_amount;
        
        
        if (data.valid_from !== undefined) updatePayload.valid_from = data.valid_from;
        
        
        if (data.valid_until !== undefined) updatePayload.valid_until = data.valid_until;
        
        
        if (data.minimum_stay_nights !== undefined) updatePayload.minimum_stay_nights = data.minimum_stay_nights;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await negotiated_rates.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.property !== undefined) {
            await negotiated_rates.setProperty(
              
              data.property,
              
              { transaction }
            );
        }
        
        if (data.unit_type !== undefined) {
            await negotiated_rates.setUnit_type(
              
              data.unit_type,
              
              { transaction }
            );
        }
        

        
        

        

        return negotiated_rates;
    }

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

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

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


        return negotiated_rates;
    }

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

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

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

        await negotiated_rates.destroy({
            transaction
        });

        return negotiated_rates;
    }

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

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

        if (!negotiated_rates) {
            return negotiated_rates;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await negotiated_rates.getOrganization({
            transaction
        });
        
        
        output.property = await negotiated_rates.getProperty({
            transaction
        });
        
        
        output.unit_type = await negotiated_rates.getUnit_type({
            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.organizations,
        as: 'organization',
        
      },

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

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



    ];

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

            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'negotiated_rates',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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


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

        where = {
          ...where,
          organizationId: {[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.negotiated_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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

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

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

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

    
};

