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

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

        const travel_bookings = await db.travel_bookings.create(
            {
                id: data.id || undefined,
        
        booking_type: data.booking_type
        ||
        null
            ,
            
        provider: data.provider
        ||
        null
            ,
            
        external_booking_key: data.external_booking_key
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        amount: data.amount
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        booked_at: data.booked_at
        ||
        null
            ,
            
        details: data.details
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await travel_bookings.setTravel_request( data.travel_request || null, {
            transaction,
        });
        
        await travel_bookings.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.travel_bookings.getTableName(),
                belongsToColumn: 'itinerary_files',
                belongsToId: travel_bookings.id,
            },
            data.itinerary_files,
            options,
        );
        

        return travel_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 travel_bookingsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                booking_type: item.booking_type
            ||
            null
            ,
            
                provider: item.provider
            ||
            null
            ,
            
                external_booking_key: item.external_booking_key
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                amount: item.amount
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                booked_at: item.booked_at
            ||
            null
            ,
            
                details: item.details
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < travel_bookings.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.travel_bookings.getTableName(),
                    belongsToColumn: 'itinerary_files',
                    belongsToId: travel_bookings[i].id,
                },
                data[i].itinerary_files,
                options,
            );
        }
        

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


        

        const updatePayload = {};
        
        if (data.booking_type !== undefined) updatePayload.booking_type = data.booking_type;
        
        
        if (data.provider !== undefined) updatePayload.provider = data.provider;
        
        
        if (data.external_booking_key !== undefined) updatePayload.external_booking_key = data.external_booking_key;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.amount !== undefined) updatePayload.amount = data.amount;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.booked_at !== undefined) updatePayload.booked_at = data.booked_at;
        
        
        if (data.details !== undefined) updatePayload.details = data.details;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.travel_request !== undefined) {
            await travel_bookings.setTravel_request(
              
              data.travel_request,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await travel_bookings.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.travel_bookings.getTableName(),
                belongsToColumn: 'itinerary_files',
                belongsToId: travel_bookings.id,
            },
            data.itinerary_files,
            options,
        );
        

        return travel_bookings;
    }

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

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

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


        return travel_bookings;
    }

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

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

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

        await travel_bookings.destroy({
            transaction
        });

        return travel_bookings;
    }

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

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

        if (!travel_bookings) {
            return travel_bookings;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.travel_request = await travel_bookings.getTravel_request({
            transaction
        });
        
        
        output.itinerary_files = await travel_bookings.getItinerary_files({
            transaction
        });
        
        
        output.organizations = await travel_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.travel_requests,
        as: 'travel_request',
        
        where: filter.travel_request ? {
          [Op.or]: [
            { id: { [Op.in]: filter.travel_request.split('|').map(term => Utils.uuid(term)) } },
            {
              destination: {
                [Op.or]: filter.travel_request.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.organizations,
        as: 'organizations',
        
      },



      {
        model: db.file,
        as: 'itinerary_files',
      },

    ];

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

            
            if (filter.provider) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'travel_bookings',
                        'provider',
                        filter.provider,
                    ),
                };
            }
            
            if (filter.external_booking_key) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'travel_bookings',
                        'external_booking_key',
                        filter.external_booking_key,
                    ),
                };
            }
            
            if (filter.currency) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'travel_bookings',
                        'currency',
                        filter.currency,
                    ),
                };
            }
            
            if (filter.details) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'travel_bookings',
                        'details',
                        filter.details,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.booking_type) {
                where = {
                    ...where,
                booking_type: filter.booking_type,
            };
            }
            
            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_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(
                        'travel_bookings',
                        'provider',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

