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

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

        const reservations = await db.reservations.create(
            {
                id: data.id || undefined,
        
        reservation_number: data.reservation_number
        ||
        null
            ,
            
        check_in_at: data.check_in_at
        ||
        null
            ,
            
        check_out_at: data.check_out_at
        ||
        null
            ,
            
        adults: data.adults
        ||
        null
            ,
            
        children: data.children
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        total_amount: data.total_amount
        ||
        null
            ,
            
        tax_amount: data.tax_amount
        ||
        null
            ,
            
        deposit_amount: data.deposit_amount
        ||
        null
            ,
            
        special_requests: data.special_requests
        ||
        null
            ,
            
        internal_notes: data.internal_notes
        ||
        null
            ,
            
        cancelled_at: data.cancelled_at
        ||
        null
            ,
            
        cancellation_reason: data.cancellation_reason
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await reservations.setHotel( data.hotel || null, {
            transaction,
        });
        
        await reservations.setGuest( data.guest || null, {
            transaction,
        });
        
        await reservations.setRoom( data.room || null, {
            transaction,
        });
        
        await reservations.setRoom_type( data.room_type || null, {
            transaction,
        });
        
        await reservations.setRate_plan( data.rate_plan || null, {
            transaction,
        });
        
        await reservations.setSales_channel( data.sales_channel || null, {
            transaction,
        });
        
        await reservations.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return reservations;
    }
    

    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 reservationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                reservation_number: item.reservation_number
            ||
            null
            ,
            
                check_in_at: item.check_in_at
            ||
            null
            ,
            
                check_out_at: item.check_out_at
            ||
            null
            ,
            
                adults: item.adults
            ||
            null
            ,
            
                children: item.children
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                total_amount: item.total_amount
            ||
            null
            ,
            
                tax_amount: item.tax_amount
            ||
            null
            ,
            
                deposit_amount: item.deposit_amount
            ||
            null
            ,
            
                special_requests: item.special_requests
            ||
            null
            ,
            
                internal_notes: item.internal_notes
            ||
            null
            ,
            
                cancelled_at: item.cancelled_at
            ||
            null
            ,
            
                cancellation_reason: item.cancellation_reason
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return reservations;
    }

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


        

        const updatePayload = {};
        
        if (data.reservation_number !== undefined) updatePayload.reservation_number = data.reservation_number;
        
        
        if (data.check_in_at !== undefined) updatePayload.check_in_at = data.check_in_at;
        
        
        if (data.check_out_at !== undefined) updatePayload.check_out_at = data.check_out_at;
        
        
        if (data.adults !== undefined) updatePayload.adults = data.adults;
        
        
        if (data.children !== undefined) updatePayload.children = data.children;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.total_amount !== undefined) updatePayload.total_amount = data.total_amount;
        
        
        if (data.tax_amount !== undefined) updatePayload.tax_amount = data.tax_amount;
        
        
        if (data.deposit_amount !== undefined) updatePayload.deposit_amount = data.deposit_amount;
        
        
        if (data.special_requests !== undefined) updatePayload.special_requests = data.special_requests;
        
        
        if (data.internal_notes !== undefined) updatePayload.internal_notes = data.internal_notes;
        
        
        if (data.cancelled_at !== undefined) updatePayload.cancelled_at = data.cancelled_at;
        
        
        if (data.cancellation_reason !== undefined) updatePayload.cancellation_reason = data.cancellation_reason;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.hotel !== undefined) {
            await reservations.setHotel(
              
              data.hotel,
              
              { transaction }
            );
        }
        
        if (data.guest !== undefined) {
            await reservations.setGuest(
              
              data.guest,
              
              { transaction }
            );
        }
        
        if (data.room !== undefined) {
            await reservations.setRoom(
              
              data.room,
              
              { transaction }
            );
        }
        
        if (data.room_type !== undefined) {
            await reservations.setRoom_type(
              
              data.room_type,
              
              { transaction }
            );
        }
        
        if (data.rate_plan !== undefined) {
            await reservations.setRate_plan(
              
              data.rate_plan,
              
              { transaction }
            );
        }
        
        if (data.sales_channel !== undefined) {
            await reservations.setSales_channel(
              
              data.sales_channel,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await reservations.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return reservations;
    }

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

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

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


        return reservations;
    }

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

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

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

        await reservations.destroy({
            transaction
        });

        return reservations;
    }

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

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

        if (!reservations) {
            return reservations;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.reservation_guests_reservation = await reservations.getReservation_guests_reservation({
            transaction
        });
        
        
        output.stay_folios_reservation = await reservations.getStay_folios_reservation({
            transaction
        });
        
        
        
        output.payments_reservation = await reservations.getPayments_reservation({
            transaction
        });
        
        
        
        
        
        
        output.notifications_reservation = await reservations.getNotifications_reservation({
            transaction
        });
        
        
        
        
        
        
        
        output.hotel = await reservations.getHotel({
            transaction
        });
        
        
        output.guest = await reservations.getGuest({
            transaction
        });
        
        
        output.room = await reservations.getRoom({
            transaction
        });
        
        
        output.room_type = await reservations.getRoom_type({
            transaction
        });
        
        
        output.rate_plan = await reservations.getRate_plan({
            transaction
        });
        
        
        output.sales_channel = await reservations.getSales_channel({
            transaction
        });
        
        
        output.organizations = await reservations.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.guests,
        as: 'guest',
        
        where: filter.guest ? {
          [Op.or]: [
            { id: { [Op.in]: filter.guest.split('|').map(term => Utils.uuid(term)) } },
            {
              last_name: {
                [Op.or]: filter.guest.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.rooms,
        as: 'room',
        
        where: filter.room ? {
          [Op.or]: [
            { id: { [Op.in]: filter.room.split('|').map(term => Utils.uuid(term)) } },
            {
              room_number: {
                [Op.or]: filter.room.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.sales_channels,
        as: 'sales_channel',
        
        where: filter.sales_channel ? {
          [Op.or]: [
            { id: { [Op.in]: filter.sales_channel.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.sales_channel.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.reservation_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'reservations',
                        'reservation_number',
                        filter.reservation_number,
                    ),
                };
            }
            
            if (filter.special_requests) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'reservations',
                        'special_requests',
                        filter.special_requests,
                    ),
                };
            }
            
            if (filter.internal_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'reservations',
                        'internal_notes',
                        filter.internal_notes,
                    ),
                };
            }
            
            if (filter.cancellation_reason) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'reservations',
                        'cancellation_reason',
                        filter.cancellation_reason,
                    ),
                };
            }
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


      

      

      

      

      

      

      
      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.reservations.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(
                        'reservations',
                        'reservation_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

