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

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

        const trips = await db.trips.create(
            {
                id: data.id || undefined,
        
        trip_no: data.trip_no
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        planned_start_at: data.planned_start_at
        ||
        null
            ,
            
        planned_end_at: data.planned_end_at
        ||
        null
            ,
            
        started_at: data.started_at
        ||
        null
            ,
            
        finished_at: data.finished_at
        ||
        null
            ,
            
        start_odometer_km: data.start_odometer_km
        ||
        null
            ,
            
        end_odometer_km: data.end_odometer_km
        ||
        null
            ,
            
        distance_km: data.distance_km
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await trips.setCompany( data.company || null, {
            transaction,
        });
        
        await trips.setDispatcher_user( data.dispatcher_user || null, {
            transaction,
        });
        
        await trips.setDriver( data.driver || null, {
            transaction,
        });
        
        await trips.setVehicle( data.vehicle || null, {
            transaction,
        });
        
        await trips.setTrailer( data.trailer || null, {
            transaction,
        });
        

        

        

        return trips;
    }
    

    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 tripsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                trip_no: item.trip_no
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                planned_start_at: item.planned_start_at
            ||
            null
            ,
            
                planned_end_at: item.planned_end_at
            ||
            null
            ,
            
                started_at: item.started_at
            ||
            null
            ,
            
                finished_at: item.finished_at
            ||
            null
            ,
            
                start_odometer_km: item.start_odometer_km
            ||
            null
            ,
            
                end_odometer_km: item.end_odometer_km
            ||
            null
            ,
            
                distance_km: item.distance_km
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return trips;
    }

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

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


        

        const updatePayload = {};
        
        if (data.trip_no !== undefined) updatePayload.trip_no = data.trip_no;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.planned_start_at !== undefined) updatePayload.planned_start_at = data.planned_start_at;
        
        
        if (data.planned_end_at !== undefined) updatePayload.planned_end_at = data.planned_end_at;
        
        
        if (data.started_at !== undefined) updatePayload.started_at = data.started_at;
        
        
        if (data.finished_at !== undefined) updatePayload.finished_at = data.finished_at;
        
        
        if (data.start_odometer_km !== undefined) updatePayload.start_odometer_km = data.start_odometer_km;
        
        
        if (data.end_odometer_km !== undefined) updatePayload.end_odometer_km = data.end_odometer_km;
        
        
        if (data.distance_km !== undefined) updatePayload.distance_km = data.distance_km;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await trips.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        
        if (data.dispatcher_user !== undefined) {
            await trips.setDispatcher_user(
              
              data.dispatcher_user,
              
              { transaction }
            );
        }
        
        if (data.driver !== undefined) {
            await trips.setDriver(
              
              data.driver,
              
              { transaction }
            );
        }
        
        if (data.vehicle !== undefined) {
            await trips.setVehicle(
              
              data.vehicle,
              
              { transaction }
            );
        }
        
        if (data.trailer !== undefined) {
            await trips.setTrailer(
              
              data.trailer,
              
              { transaction }
            );
        }
        

        
        

        

        return trips;
    }

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

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

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


        return trips;
    }

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

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

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

        await trips.destroy({
            transaction
        });

        return trips;
    }

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

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

        if (!trips) {
            return trips;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.trip_loads_trip = await trips.getTrip_loads_trip({
            transaction
        });
        
        
        
        
        output.invoice_lines_trip = await trips.getInvoice_lines_trip({
            transaction
        });
        
        
        
        output.cost_items_trip = await trips.getCost_items_trip({
            transaction
        });
        
        
        
        
        
        
        output.company = await trips.getCompany({
            transaction
        });
        
        
        output.dispatcher_user = await trips.getDispatcher_user({
            transaction
        });
        
        
        output.driver = await trips.getDriver({
            transaction
        });
        
        
        output.vehicle = await trips.getVehicle({
            transaction
        });
        
        
        output.trailer = await trips.getTrailer({
            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.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: 'dispatcher_user',
        
        where: filter.dispatcher_user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.dispatcher_user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.dispatcher_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.employees,
        as: 'driver',
        
        where: filter.driver ? {
          [Op.or]: [
            { id: { [Op.in]: filter.driver.split('|').map(term => Utils.uuid(term)) } },
            {
              last_name: {
                [Op.or]: filter.driver.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)) } },
            {
              plate_number: {
                [Op.or]: filter.vehicle.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.trip_no) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'trips',
                        'trip_no',
                        filter.trip_no,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'trips',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    distance_km: {
                    ...where.distance_km,
                            [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.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.trips.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(
                        'trips',
                        'trip_no',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

