
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,
        
        type: data.type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        ownership: data.ownership
        ||
        null
            ,
            
        plate_number: data.plate_number
        ||
        null
            ,
            
        vin: data.vin
        ||
        null
            ,
            
        brand: data.brand
        ||
        null
            ,
            
        model: data.model
        ||
        null
            ,
            
        variant: data.variant
        ||
        null
            ,
            
        year: data.year
        ||
        null
            ,
            
        first_registration_at: data.first_registration_at
        ||
        null
            ,
            
        fuel_type: data.fuel_type
        ||
        null
            ,
            
        emission_class: data.emission_class
        ||
        null
            ,
            
        gross_weight_kg: data.gross_weight_kg
        ||
        null
            ,
            
        curb_weight_kg: data.curb_weight_kg
        ||
        null
            ,
            
        payload_kg: data.payload_kg
        ||
        null
            ,
            
        axle_count: data.axle_count
        ||
        null
            ,
            
        has_liftgate: data.has_liftgate
        ||
        false
        
            ,
            
        tachograph_type: data.tachograph_type
        ||
        null
            ,
            
        tachograph_serial: data.tachograph_serial
        ||
        null
            ,
            
        tachograph_last_calibration_at: data.tachograph_last_calibration_at
        ||
        null
            ,
            
        tachograph_next_calibration_at: data.tachograph_next_calibration_at
        ||
        null
            ,
            
        toll_provider: data.toll_provider
        ||
        null
            ,
            
        toll_obu_serial: data.toll_obu_serial
        ||
        null
            ,
            
        toll_contract_no: data.toll_contract_no
        ||
        null
            ,
            
        insurance_notes: data.insurance_notes
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await vehicles.setCompany( data.company || null, {
            transaction,
        });
        

        

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

        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,
                
                type: item.type
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                ownership: item.ownership
            ||
            null
            ,
            
                plate_number: item.plate_number
            ||
            null
            ,
            
                vin: item.vin
            ||
            null
            ,
            
                brand: item.brand
            ||
            null
            ,
            
                model: item.model
            ||
            null
            ,
            
                variant: item.variant
            ||
            null
            ,
            
                year: item.year
            ||
            null
            ,
            
                first_registration_at: item.first_registration_at
            ||
            null
            ,
            
                fuel_type: item.fuel_type
            ||
            null
            ,
            
                emission_class: item.emission_class
            ||
            null
            ,
            
                gross_weight_kg: item.gross_weight_kg
            ||
            null
            ,
            
                curb_weight_kg: item.curb_weight_kg
            ||
            null
            ,
            
                payload_kg: item.payload_kg
            ||
            null
            ,
            
                axle_count: item.axle_count
            ||
            null
            ,
            
                has_liftgate: item.has_liftgate
            ||
            false
        
            ,
            
                tachograph_type: item.tachograph_type
            ||
            null
            ,
            
                tachograph_serial: item.tachograph_serial
            ||
            null
            ,
            
                tachograph_last_calibration_at: item.tachograph_last_calibration_at
            ||
            null
            ,
            
                tachograph_next_calibration_at: item.tachograph_next_calibration_at
            ||
            null
            ,
            
                toll_provider: item.toll_provider
            ||
            null
            ,
            
                toll_obu_serial: item.toll_obu_serial
            ||
            null
            ,
            
                toll_contract_no: item.toll_contract_no
            ||
            null
            ,
            
                insurance_notes: item.insurance_notes
            ||
            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 vehicles = await db.vehicles.bulkCreate(vehiclesData, { transaction });

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

        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.type !== undefined) updatePayload.type = data.type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.ownership !== undefined) updatePayload.ownership = data.ownership;
        
        
        if (data.plate_number !== undefined) updatePayload.plate_number = data.plate_number;
        
        
        if (data.vin !== undefined) updatePayload.vin = data.vin;
        
        
        if (data.brand !== undefined) updatePayload.brand = data.brand;
        
        
        if (data.model !== undefined) updatePayload.model = data.model;
        
        
        if (data.variant !== undefined) updatePayload.variant = data.variant;
        
        
        if (data.year !== undefined) updatePayload.year = data.year;
        
        
        if (data.first_registration_at !== undefined) updatePayload.first_registration_at = data.first_registration_at;
        
        
        if (data.fuel_type !== undefined) updatePayload.fuel_type = data.fuel_type;
        
        
        if (data.emission_class !== undefined) updatePayload.emission_class = data.emission_class;
        
        
        if (data.gross_weight_kg !== undefined) updatePayload.gross_weight_kg = data.gross_weight_kg;
        
        
        if (data.curb_weight_kg !== undefined) updatePayload.curb_weight_kg = data.curb_weight_kg;
        
        
        if (data.payload_kg !== undefined) updatePayload.payload_kg = data.payload_kg;
        
        
        if (data.axle_count !== undefined) updatePayload.axle_count = data.axle_count;
        
        
        if (data.has_liftgate !== undefined) updatePayload.has_liftgate = data.has_liftgate;
        
        
        if (data.tachograph_type !== undefined) updatePayload.tachograph_type = data.tachograph_type;
        
        
        if (data.tachograph_serial !== undefined) updatePayload.tachograph_serial = data.tachograph_serial;
        
        
        if (data.tachograph_last_calibration_at !== undefined) updatePayload.tachograph_last_calibration_at = data.tachograph_last_calibration_at;
        
        
        if (data.tachograph_next_calibration_at !== undefined) updatePayload.tachograph_next_calibration_at = data.tachograph_next_calibration_at;
        
        
        if (data.toll_provider !== undefined) updatePayload.toll_provider = data.toll_provider;
        
        
        if (data.toll_obu_serial !== undefined) updatePayload.toll_obu_serial = data.toll_obu_serial;
        
        
        if (data.toll_contract_no !== undefined) updatePayload.toll_contract_no = data.toll_contract_no;
        
        
        if (data.insurance_notes !== undefined) updatePayload.insurance_notes = data.insurance_notes;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await vehicles.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        

        
        

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

        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.vehicle_trailer_links_vehicle = await vehicles.getVehicle_trailer_links_vehicle({
            transaction
        });
        
        
        output.vehicle_inspections_vehicle = await vehicles.getVehicle_inspections_vehicle({
            transaction
        });
        
        
        output.vehicle_maintenances_vehicle = await vehicles.getVehicle_maintenances_vehicle({
            transaction
        });
        
        
        output.vehicle_insurances_vehicle = await vehicles.getVehicle_insurances_vehicle({
            transaction
        });
        
        
        output.vehicle_documents_vehicle = await vehicles.getVehicle_documents_vehicle({
            transaction
        });
        
        
        
        output.driver_vehicle_assignments_vehicle = await vehicles.getDriver_vehicle_assignments_vehicle({
            transaction
        });
        
        
        
        
        
        output.trips_vehicle = await vehicles.getTrips_vehicle({
            transaction
        });
        
        
        
        
        
        
        
        output.cost_items_vehicle = await vehicles.getCost_items_vehicle({
            transaction
        });
        
        
        
        
        
        
        output.company = await vehicles.getCompany({
            transaction
        });
        
        
        output.photo = await vehicles.getPhoto({
            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.file,
        as: 'photo',
      },

    ];

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

            
            if (filter.plate_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicles',
                        'plate_number',
                        filter.plate_number,
                    ),
                };
            }
            
            if (filter.vin) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicles',
                        'vin',
                        filter.vin,
                    ),
                };
            }
            
            if (filter.brand) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicles',
                        'brand',
                        filter.brand,
                    ),
                };
            }
            
            if (filter.model) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicles',
                        'model',
                        filter.model,
                    ),
                };
            }
            
            if (filter.variant) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicles',
                        'variant',
                        filter.variant,
                    ),
                };
            }
            
            if (filter.tachograph_serial) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicles',
                        'tachograph_serial',
                        filter.tachograph_serial,
                    ),
                };
            }
            
            if (filter.toll_obu_serial) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicles',
                        'toll_obu_serial',
                        filter.toll_obu_serial,
                    ),
                };
            }
            
            if (filter.toll_contract_no) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicles',
                        'toll_contract_no',
                        filter.toll_contract_no,
                    ),
                };
            }
            
            if (filter.insurance_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicles',
                        'insurance_notes',
                        filter.insurance_notes,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicles',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.type) {
                where = {
                    ...where,
                type: filter.type,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            
            if (filter.ownership) {
                where = {
                    ...where,
                ownership: filter.ownership,
            };
            }
            
            if (filter.fuel_type) {
                where = {
                    ...where,
                fuel_type: filter.fuel_type,
            };
            }
            
            if (filter.emission_class) {
                where = {
                    ...where,
                emission_class: filter.emission_class,
            };
            }
            
            if (filter.has_liftgate) {
                where = {
                    ...where,
                has_liftgate: filter.has_liftgate,
            };
            }
            
            if (filter.tachograph_type) {
                where = {
                    ...where,
                tachograph_type: filter.tachograph_type,
            };
            }
            
            if (filter.toll_provider) {
                where = {
                    ...where,
                toll_provider: filter.toll_provider,
            };
            }
            


      



            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',
                        'plate_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

