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

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

        const bookings = await db.bookings.create(
            {
                id: data.id || undefined,
        
        booking_code: data.booking_code
        ||
        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
            ,
            
        source: data.source
        ||
        null
            ,
            
        total_amount: data.total_amount
        ||
        null
            ,
            
        tax_amount: data.tax_amount
        ||
        null
            ,
            
        city_tax_amount: data.city_tax_amount
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        deposit_amount: data.deposit_amount
        ||
        null
            ,
            
        deposit_status: data.deposit_status
        ||
        null
            ,
            
        special_requests: data.special_requests
        ||
        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 bookings.setHotel( data.hotel || null, {
            transaction,
        });
        
        await bookings.setPrimary_guest( data.primary_guest || null, {
            transaction,
        });
        
        await bookings.setRoom_type( data.room_type || null, {
            transaction,
        });
        
        await bookings.setRate_plan( data.rate_plan || null, {
            transaction,
        });
        

        
        await bookings.setReserved_rooms(data.reserved_rooms || [], {
            transaction,
        });
        
        await bookings.setBooking_guests(data.booking_guests || [], {
            transaction,
        });
        
        await bookings.setPayments(data.payments || [], {
            transaction,
        });
        
        await bookings.setMessages(data.messages || [], {
            transaction,
        });
        

        

        return bookings;
    }
    

    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 bookingsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                booking_code: item.booking_code
            ||
            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
            ,
            
                source: item.source
            ||
            null
            ,
            
                total_amount: item.total_amount
            ||
            null
            ,
            
                tax_amount: item.tax_amount
            ||
            null
            ,
            
                city_tax_amount: item.city_tax_amount
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                deposit_amount: item.deposit_amount
            ||
            null
            ,
            
                deposit_status: item.deposit_status
            ||
            null
            ,
            
                special_requests: item.special_requests
            ||
            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 bookings = await db.bookings.bulkCreate(bookingsData, { transaction });

        // For each item created, replace relation files
        

        return bookings;
    }

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

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


        

        const updatePayload = {};
        
        if (data.booking_code !== undefined) updatePayload.booking_code = data.booking_code;
        
        
        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.source !== undefined) updatePayload.source = data.source;
        
        
        if (data.total_amount !== undefined) updatePayload.total_amount = data.total_amount;
        
        
        if (data.tax_amount !== undefined) updatePayload.tax_amount = data.tax_amount;
        
        
        if (data.city_tax_amount !== undefined) updatePayload.city_tax_amount = data.city_tax_amount;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.deposit_amount !== undefined) updatePayload.deposit_amount = data.deposit_amount;
        
        
        if (data.deposit_status !== undefined) updatePayload.deposit_status = data.deposit_status;
        
        
        if (data.special_requests !== undefined) updatePayload.special_requests = data.special_requests;
        
        
        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 bookings.update(updatePayload, {transaction});

        
        
        if (data.hotel !== undefined) {
            await bookings.setHotel(
              
              data.hotel,
              
              { transaction }
            );
        }
        
        if (data.primary_guest !== undefined) {
            await bookings.setPrimary_guest(
              
              data.primary_guest,
              
              { transaction }
            );
        }
        
        if (data.room_type !== undefined) {
            await bookings.setRoom_type(
              
              data.room_type,
              
              { transaction }
            );
        }
        
        if (data.rate_plan !== undefined) {
            await bookings.setRate_plan(
              
              data.rate_plan,
              
              { transaction }
            );
        }
        

        
        
        if (data.reserved_rooms !== undefined) {
            await bookings.setReserved_rooms(data.reserved_rooms, { transaction });
        }
        
        if (data.booking_guests !== undefined) {
            await bookings.setBooking_guests(data.booking_guests, { transaction });
        }
        
        if (data.payments !== undefined) {
            await bookings.setPayments(data.payments, { transaction });
        }
        
        if (data.messages !== undefined) {
            await bookings.setMessages(data.messages, { transaction });
        }
        

        

        return bookings;
    }

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

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

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


        return bookings;
    }

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

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

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

        await bookings.destroy({
            transaction
        });

        return bookings;
    }

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

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

        if (!bookings) {
            return bookings;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.booking_guests_booking = await bookings.getBooking_guests_booking({
            transaction
        });
        
        
        output.payments_booking = await bookings.getPayments_booking({
            transaction
        });
        
        
        output.invoices_booking = await bookings.getInvoices_booking({
            transaction
        });
        
        
        output.messages_booking = await bookings.getMessages_booking({
            transaction
        });
        
        
        
        output.booking_discounts_booking = await bookings.getBooking_discounts_booking({
            transaction
        });
        
        
        
        output.service_requests_booking = await bookings.getService_requests_booking({
            transaction
        });
        
        
        
        
        
        output.hotel = await bookings.getHotel({
            transaction
        });
        
        
        output.primary_guest = await bookings.getPrimary_guest({
            transaction
        });
        
        
        output.room_type = await bookings.getRoom_type({
            transaction
        });
        
        
        output.rate_plan = await bookings.getRate_plan({
            transaction
        });
        
        
        output.reserved_rooms = await bookings.getReserved_rooms({
            transaction
        });
        
        
        output.booking_guests = await bookings.getBooking_guests({
            transaction
        });
        
        
        output.payments = await bookings.getPayments({
            transaction
        });
        
        
        output.messages = await bookings.getMessages({
            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}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.guests,
        as: 'primary_guest',
        
        where: filter.primary_guest ? {
          [Op.or]: [
            { id: { [Op.in]: filter.primary_guest.split('|').map(term => Utils.uuid(term)) } },
            {
              email: {
                [Op.or]: filter.primary_guest.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.rooms,
        as: 'reserved_rooms',
        required: false,
      },

      {
        model: db.booking_guests,
        as: 'booking_guests',
        required: false,
      },

      {
        model: db.payments,
        as: 'payments',
        required: false,
      },

      {
        model: db.messages,
        as: 'messages',
        required: false,
      },


    ];

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

            
            if (filter.booking_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'bookings',
                        'booking_code',
                        filter.booking_code,
                    ),
                };
            }
            
            if (filter.currency) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'bookings',
                        'currency',
                        filter.currency,
                    ),
                };
            }
            
            if (filter.special_requests) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'bookings',
                        'special_requests',
                        filter.special_requests,
                    ),
                };
            }
            
            if (filter.cancellation_reason) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'bookings',
                        '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.city_tax_amountRange) {
                const [start, end] = filter.city_tax_amountRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    city_tax_amount: {
                    ...where.city_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.source) {
                where = {
                    ...where,
                source: filter.source,
            };
            }
            
            if (filter.deposit_status) {
                where = {
                    ...where,
                deposit_status: filter.deposit_status,
            };
            }
            


      

      

      

      


      if (filter.reserved_rooms) {
        const searchTerms = filter.reserved_rooms.split('|');

        include = [
          {
            model: db.rooms,
            as: 'reserved_rooms_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  room_number: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }

      if (filter.booking_guests) {
        const searchTerms = filter.booking_guests.split('|');

        include = [
          {
            model: db.booking_guests,
            as: 'booking_guests_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  guest_role: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }

      if (filter.payments) {
        const searchTerms = filter.payments.split('|');

        include = [
          {
            model: db.payments,
            as: 'payments_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  provider_reference: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }

      if (filter.messages) {
        const searchTerms = filter.messages.split('|');

        include = [
          {
            model: db.messages,
            as: 'messages_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  subject: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


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

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

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

    
};

