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

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

        const travel_requests = await db.travel_requests.create(
            {
                id: data.id || undefined,
        
        origin: data.origin
        ||
        null
            ,
            
        destination: data.destination
        ||
        null
            ,
            
        depart_at: data.depart_at
        ||
        null
            ,
            
        return_at: data.return_at
        ||
        null
            ,
            
        trip_type: data.trip_type
        ||
        null
            ,
            
        cabin: data.cabin
        ||
        null
            ,
            
        travelers_count: data.travelers_count
        ||
        null
            ,
            
        max_budget: data.max_budget
        ||
        null
            ,
            
        preferences: data.preferences
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await travel_requests.setUser( data.user || null, {
            transaction,
        });
        
        await travel_requests.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return travel_requests;
    }
    

    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 travel_requestsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                origin: item.origin
            ||
            null
            ,
            
                destination: item.destination
            ||
            null
            ,
            
                depart_at: item.depart_at
            ||
            null
            ,
            
                return_at: item.return_at
            ||
            null
            ,
            
                trip_type: item.trip_type
            ||
            null
            ,
            
                cabin: item.cabin
            ||
            null
            ,
            
                travelers_count: item.travelers_count
            ||
            null
            ,
            
                max_budget: item.max_budget
            ||
            null
            ,
            
                preferences: item.preferences
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return travel_requests;
    }

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


        

        const updatePayload = {};
        
        if (data.origin !== undefined) updatePayload.origin = data.origin;
        
        
        if (data.destination !== undefined) updatePayload.destination = data.destination;
        
        
        if (data.depart_at !== undefined) updatePayload.depart_at = data.depart_at;
        
        
        if (data.return_at !== undefined) updatePayload.return_at = data.return_at;
        
        
        if (data.trip_type !== undefined) updatePayload.trip_type = data.trip_type;
        
        
        if (data.cabin !== undefined) updatePayload.cabin = data.cabin;
        
        
        if (data.travelers_count !== undefined) updatePayload.travelers_count = data.travelers_count;
        
        
        if (data.max_budget !== undefined) updatePayload.max_budget = data.max_budget;
        
        
        if (data.preferences !== undefined) updatePayload.preferences = data.preferences;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await travel_requests.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await travel_requests.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return travel_requests;
    }

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

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

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


        return travel_requests;
    }

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

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

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

        await travel_requests.destroy({
            transaction
        });

        return travel_requests;
    }

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

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

        if (!travel_requests) {
            return travel_requests;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.travel_bookings_travel_request = await travel_requests.getTravel_bookings_travel_request({
            transaction
        });
        
        
        
        
        
        
        output.user = await travel_requests.getUser({
            transaction
        });
        
        
        output.organizations = await travel_requests.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.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.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.origin) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'travel_requests',
                        'origin',
                        filter.origin,
                    ),
                };
            }
            
            if (filter.destination) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'travel_requests',
                        'destination',
                        filter.destination,
                    ),
                };
            }
            
            if (filter.preferences) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'travel_requests',
                        'preferences',
                        filter.preferences,
                    ),
                };
            }
            

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.trip_type) {
                where = {
                    ...where,
                trip_type: filter.trip_type,
            };
            }
            
            if (filter.cabin) {
                where = {
                    ...where,
                cabin: filter.cabin,
            };
            }
            
            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.travel_requests.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(
                        'travel_requests',
                        'destination',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

