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

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

        const trip_loads = await db.trip_loads.create(
            {
                id: data.id || undefined,
        
        sequence: data.sequence
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await trip_loads.setTrip( data.trip || null, {
            transaction,
        });
        
        await trip_loads.setLoad( data.load || null, {
            transaction,
        });
        

        

        

        return trip_loads;
    }
    

    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 trip_loadsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                sequence: item.sequence
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return trip_loads;
    }

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

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


        

        const updatePayload = {};
        
        if (data.sequence !== undefined) updatePayload.sequence = data.sequence;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.trip !== undefined) {
            await trip_loads.setTrip(
              
              data.trip,
              
              { transaction }
            );
        }
        
        if (data.load !== undefined) {
            await trip_loads.setLoad(
              
              data.load,
              
              { transaction }
            );
        }
        

        
        

        

        return trip_loads;
    }

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

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

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


        return trip_loads;
    }

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

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

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

        await trip_loads.destroy({
            transaction
        });

        return trip_loads;
    }

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

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

        if (!trip_loads) {
            return trip_loads;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.trip = await trip_loads.getTrip({
            transaction
        });
        
        
        output.load = await trip_loads.getLoad({
            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.trips,
        as: 'trip',
        
        where: filter.trip ? {
          [Op.or]: [
            { id: { [Op.in]: filter.trip.split('|').map(term => Utils.uuid(term)) } },
            {
              trip_no: {
                [Op.or]: filter.trip.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            

            
            

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

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

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

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

            


      

      



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

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

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

    
};

