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

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

        const trucks = await db.trucks.create(
            {
                id: data.id || undefined,
        
        truck_code: data.truck_code
        ||
        null
            ,
            
        registration_number: data.registration_number
        ||
        null
            ,
            
        driver_name: data.driver_name
        ||
        null
            ,
            
        driver_phone: data.driver_phone
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        last_latitude: data.last_latitude
        ||
        null
            ,
            
        last_longitude: data.last_longitude
        ||
        null
            ,
            
        last_ping_at: data.last_ping_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return trucks;
    }
    

    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 trucksData = data.map((item, index) => ({
                id: item.id || undefined,
                
                truck_code: item.truck_code
            ||
            null
            ,
            
                registration_number: item.registration_number
            ||
            null
            ,
            
                driver_name: item.driver_name
            ||
            null
            ,
            
                driver_phone: item.driver_phone
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                last_latitude: item.last_latitude
            ||
            null
            ,
            
                last_longitude: item.last_longitude
            ||
            null
            ,
            
                last_ping_at: item.last_ping_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return trucks;
    }

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

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


        

        const updatePayload = {};
        
        if (data.truck_code !== undefined) updatePayload.truck_code = data.truck_code;
        
        
        if (data.registration_number !== undefined) updatePayload.registration_number = data.registration_number;
        
        
        if (data.driver_name !== undefined) updatePayload.driver_name = data.driver_name;
        
        
        if (data.driver_phone !== undefined) updatePayload.driver_phone = data.driver_phone;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.last_latitude !== undefined) updatePayload.last_latitude = data.last_latitude;
        
        
        if (data.last_longitude !== undefined) updatePayload.last_longitude = data.last_longitude;
        
        
        if (data.last_ping_at !== undefined) updatePayload.last_ping_at = data.last_ping_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return trucks;
    }

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

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

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


        return trucks;
    }

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

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

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

        await trucks.destroy({
            transaction
        });

        return trucks;
    }

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

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

        if (!trucks) {
            return trucks;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.truck_tracking_events_truck = await trucks.getTruck_tracking_events_truck({
            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 = [



    ];

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

            
            if (filter.truck_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'trucks',
                        'truck_code',
                        filter.truck_code,
                    ),
                };
            }
            
            if (filter.registration_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'trucks',
                        'registration_number',
                        filter.registration_number,
                    ),
                };
            }
            
            if (filter.driver_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'trucks',
                        'driver_name',
                        filter.driver_name,
                    ),
                };
            }
            
            if (filter.driver_phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'trucks',
                        'driver_phone',
                        filter.driver_phone,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

    
};

