
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,
        
        pickup_at: data.pickup_at
        ||
        null
            ,
            
        dropoff_at: data.dropoff_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        payment_status: data.payment_status
        ||
        null
            ,
            
        subtotal_amount: data.subtotal_amount
        ||
        null
            ,
            
        extras_amount: data.extras_amount
        ||
        null
            ,
            
        insurance_amount: data.insurance_amount
        ||
        null
            ,
            
        discount_amount: data.discount_amount
        ||
        null
            ,
            
        tax_amount: data.tax_amount
        ||
        null
            ,
            
        total_amount: data.total_amount
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        customer_notes: data.customer_notes
        ||
        null
            ,
            
        internal_notes: data.internal_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await bookings.setCompany( data.company || null, {
            transaction,
        });
        
        await bookings.setCustomer( data.customer || null, {
            transaction,
        });
        
        await bookings.setVehicle( data.vehicle || null, {
            transaction,
        });
        
        await bookings.setPickup_branch( data.pickup_branch || null, {
            transaction,
        });
        
        await bookings.setDropoff_branch( data.dropoff_branch || null, {
            transaction,
        });
        
        await bookings.setRate_plan( data.rate_plan || null, {
            transaction,
        });
        
        await bookings.setInsurance_plan( data.insurance_plan || null, {
            transaction,
        });
        
        await bookings.setPromo_code( data.promo_code || null, {
            transaction,
        });
        
        await bookings.setOrganizations( data.organizations || null, {
            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,
                
                pickup_at: item.pickup_at
            ||
            null
            ,
            
                dropoff_at: item.dropoff_at
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                payment_status: item.payment_status
            ||
            null
            ,
            
                subtotal_amount: item.subtotal_amount
            ||
            null
            ,
            
                extras_amount: item.extras_amount
            ||
            null
            ,
            
                insurance_amount: item.insurance_amount
            ||
            null
            ,
            
                discount_amount: item.discount_amount
            ||
            null
            ,
            
                tax_amount: item.tax_amount
            ||
            null
            ,
            
                total_amount: item.total_amount
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                customer_notes: item.customer_notes
            ||
            null
            ,
            
                internal_notes: item.internal_notes
            ||
            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 globalAccess = currentUser.app_role?.globalAccess;

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


        

        const updatePayload = {};
        
        if (data.pickup_at !== undefined) updatePayload.pickup_at = data.pickup_at;
        
        
        if (data.dropoff_at !== undefined) updatePayload.dropoff_at = data.dropoff_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.payment_status !== undefined) updatePayload.payment_status = data.payment_status;
        
        
        if (data.subtotal_amount !== undefined) updatePayload.subtotal_amount = data.subtotal_amount;
        
        
        if (data.extras_amount !== undefined) updatePayload.extras_amount = data.extras_amount;
        
        
        if (data.insurance_amount !== undefined) updatePayload.insurance_amount = data.insurance_amount;
        
        
        if (data.discount_amount !== undefined) updatePayload.discount_amount = data.discount_amount;
        
        
        if (data.tax_amount !== undefined) updatePayload.tax_amount = data.tax_amount;
        
        
        if (data.total_amount !== undefined) updatePayload.total_amount = data.total_amount;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.customer_notes !== undefined) updatePayload.customer_notes = data.customer_notes;
        
        
        if (data.internal_notes !== undefined) updatePayload.internal_notes = data.internal_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await bookings.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        
        if (data.customer !== undefined) {
            await bookings.setCustomer(
              
              data.customer,
              
              { transaction }
            );
        }
        
        if (data.vehicle !== undefined) {
            await bookings.setVehicle(
              
              data.vehicle,
              
              { transaction }
            );
        }
        
        if (data.pickup_branch !== undefined) {
            await bookings.setPickup_branch(
              
              data.pickup_branch,
              
              { transaction }
            );
        }
        
        if (data.dropoff_branch !== undefined) {
            await bookings.setDropoff_branch(
              
              data.dropoff_branch,
              
              { transaction }
            );
        }
        
        if (data.rate_plan !== undefined) {
            await bookings.setRate_plan(
              
              data.rate_plan,
              
              { transaction }
            );
        }
        
        if (data.insurance_plan !== undefined) {
            await bookings.setInsurance_plan(
              
              data.insurance_plan,
              
              { transaction }
            );
        }
        
        if (data.promo_code !== undefined) {
            await bookings.setPromo_code(
              
              data.promo_code,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await bookings.setOrganizations(
              
              data.organizations,
              
              { 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_extras_booking = await bookings.getBooking_extras_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.tasks_booking = await bookings.getTasks_booking({
            transaction
        });
        
        
        
        
        
        
        output.company = await bookings.getCompany({
            transaction
        });
        
        
        output.customer = await bookings.getCustomer({
            transaction
        });
        
        
        output.vehicle = await bookings.getVehicle({
            transaction
        });
        
        
        output.pickup_branch = await bookings.getPickup_branch({
            transaction
        });
        
        
        output.dropoff_branch = await bookings.getDropoff_branch({
            transaction
        });
        
        
        output.rate_plan = await bookings.getRate_plan({
            transaction
        });
        
        
        output.insurance_plan = await bookings.getInsurance_plan({
            transaction
        });
        
        
        output.promo_code = await bookings.getPromo_code({
            transaction
        });
        
        
        output.organizations = await bookings.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.companies,
        as: 'company',
        
        where: filter.company ? {
          [Op.or]: [
            { id: { [Op.in]: filter.company.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.company.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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

      {
        model: db.branches,
        as: 'dropoff_branch',
        
        where: filter.dropoff_branch ? {
          [Op.or]: [
            { id: { [Op.in]: filter.dropoff_branch.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.dropoff_branch.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.insurance_plans,
        as: 'insurance_plan',
        
        where: filter.insurance_plan ? {
          [Op.or]: [
            { id: { [Op.in]: filter.insurance_plan.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.insurance_plan.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.promo_codes,
        as: 'promo_code',
        
        where: filter.promo_code ? {
          [Op.or]: [
            { id: { [Op.in]: filter.promo_code.split('|').map(term => Utils.uuid(term)) } },
            {
              code: {
                [Op.or]: filter.promo_code.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.currency) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'bookings',
                        'currency',
                        filter.currency,
                    ),
                };
            }
            
            if (filter.customer_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'bookings',
                        'customer_notes',
                        filter.customer_notes,
                    ),
                };
            }
            
            if (filter.internal_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'bookings',
                        'internal_notes',
                        filter.internal_notes,
                    ),
                };
            }
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
};

