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

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

        const vehicles = await db.vehicles.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        vehicle_number: data.vehicle_number
        ||
        null
            ,
            
        license_plate: data.license_plate
        ||
        null
            ,
            
        vin: data.vin
        ||
        null
            ,
            
        active: data.active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return vehicles;
    }
    

    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 vehiclesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                vehicle_number: item.vehicle_number
            ||
            null
            ,
            
                license_plate: item.license_plate
            ||
            null
            ,
            
                vin: item.vin
            ||
            null
            ,
            
                active: item.active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return vehicles;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.vehicle_number !== undefined) updatePayload.vehicle_number = data.vehicle_number;
        
        
        if (data.license_plate !== undefined) updatePayload.license_plate = data.license_plate;
        
        
        if (data.vin !== undefined) updatePayload.vin = data.vin;
        
        
        if (data.active !== undefined) updatePayload.active = data.active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return vehicles;
    }

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

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

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


        return vehicles;
    }

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

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

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

        await vehicles.destroy({
            transaction
        });

        return vehicles;
    }

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

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

        if (!vehicles) {
            return vehicles;
        }

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

        
        
        
        
        
        
        
        
        
        output.job_logs_vehicle = await vehicles.getJob_logs_vehicle({
            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.name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicles',
                        'name',
                        filter.name,
                    ),
                };
            }
            
            if (filter.vehicle_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicles',
                        'vehicle_number',
                        filter.vehicle_number,
                    ),
                };
            }
            
            if (filter.license_plate) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicles',
                        'license_plate',
                        filter.license_plate,
                    ),
                };
            }
            
            if (filter.vin) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicles',
                        'vin',
                        filter.vin,
                    ),
                };
            }
            

            
            

            

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

            
            if (filter.active) {
                where = {
                    ...where,
                active: filter.active,
            };
            }
            




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

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

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

    
};

