
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,
        
        vehicle_code: data.vehicle_code
        ||
        null
            ,
            
        plate_no: data.plate_no
        ||
        null
            ,
            
        engine_no: data.engine_no
        ||
        null
            ,
            
        chassis_no: data.chassis_no
        ||
        null
            ,
            
        make: data.make
        ||
        null
            ,
            
        model: data.model
        ||
        null
            ,
            
        year: data.year
        ||
        null
            ,
            
        colour: data.colour
        ||
        null
            ,
            
        category: data.category
        ||
        null
            ,
            
        purchase_date: data.purchase_date
        ||
        null
            ,
            
        purchase_cost: data.purchase_cost
        ||
        null
            ,
            
        ownership_type: data.ownership_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        branch: data.branch
        ||
        null
            ,
            
        odometer: data.odometer
        ||
        null
            ,
            
        insurance_policy_no: data.insurance_policy_no
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
        created_on: data.created_on
        ||
        null
            ,
            
        modified_on: data.modified_on
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await vehicles.setCompany( data.company || null, {
            transaction,
        });
        
        await vehicles.setCurrent_driver( data.current_driver || null, {
            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,
                
                vehicle_code: item.vehicle_code
            ||
            null
            ,
            
                plate_no: item.plate_no
            ||
            null
            ,
            
                engine_no: item.engine_no
            ||
            null
            ,
            
                chassis_no: item.chassis_no
            ||
            null
            ,
            
                make: item.make
            ||
            null
            ,
            
                model: item.model
            ||
            null
            ,
            
                year: item.year
            ||
            null
            ,
            
                colour: item.colour
            ||
            null
            ,
            
                category: item.category
            ||
            null
            ,
            
                purchase_date: item.purchase_date
            ||
            null
            ,
            
                purchase_cost: item.purchase_cost
            ||
            null
            ,
            
                ownership_type: item.ownership_type
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                branch: item.branch
            ||
            null
            ,
            
                odometer: item.odometer
            ||
            null
            ,
            
                insurance_policy_no: item.insurance_policy_no
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
                created_on: item.created_on
            ||
            null
            ,
            
                modified_on: item.modified_on
            ||
            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
        

        return vehicles;
    }

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

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


        

        const updatePayload = {};
        
        if (data.vehicle_code !== undefined) updatePayload.vehicle_code = data.vehicle_code;
        
        
        if (data.plate_no !== undefined) updatePayload.plate_no = data.plate_no;
        
        
        if (data.engine_no !== undefined) updatePayload.engine_no = data.engine_no;
        
        
        if (data.chassis_no !== undefined) updatePayload.chassis_no = data.chassis_no;
        
        
        if (data.make !== undefined) updatePayload.make = data.make;
        
        
        if (data.model !== undefined) updatePayload.model = data.model;
        
        
        if (data.year !== undefined) updatePayload.year = data.year;
        
        
        if (data.colour !== undefined) updatePayload.colour = data.colour;
        
        
        if (data.category !== undefined) updatePayload.category = data.category;
        
        
        if (data.purchase_date !== undefined) updatePayload.purchase_date = data.purchase_date;
        
        
        if (data.purchase_cost !== undefined) updatePayload.purchase_cost = data.purchase_cost;
        
        
        if (data.ownership_type !== undefined) updatePayload.ownership_type = data.ownership_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.branch !== undefined) updatePayload.branch = data.branch;
        
        
        if (data.odometer !== undefined) updatePayload.odometer = data.odometer;
        
        
        if (data.insurance_policy_no !== undefined) updatePayload.insurance_policy_no = data.insurance_policy_no;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        if (data.created_on !== undefined) updatePayload.created_on = data.created_on;
        
        
        if (data.modified_on !== undefined) updatePayload.modified_on = data.modified_on;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await vehicles.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        
        if (data.current_driver !== undefined) {
            await vehicles.setCurrent_driver(
              
              data.current_driver,
              
              { 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.agreements_vehicle = await vehicles.getAgreements_vehicle({
            transaction
        });
        
        
        
        output.invoices_vehicle = await vehicles.getInvoices_vehicle({
            transaction
        });
        
        
        
        output.invoice_lines_vehicle = await vehicles.getInvoice_lines_vehicle({
            transaction
        });
        
        
        
        
        
        output.vehicle_expenses_vehicle = await vehicles.getVehicle_expenses_vehicle({
            transaction
        });
        
        
        output.driver_expenses_vehicle = await vehicles.getDriver_expenses_vehicle({
            transaction
        });
        
        
        output.bills_vehicle = await vehicles.getBills_vehicle({
            transaction
        });
        
        
        
        
        output.ledger_entries_vehicle = await vehicles.getLedger_entries_vehicle({
            transaction
        });
        
        
        output.loan_schedules_vehicle = await vehicles.getLoan_schedules_vehicle({
            transaction
        });
        
        
        output.vehicle_compliance_vehicle = await vehicles.getVehicle_compliance_vehicle({
            transaction
        });
        
        
        
        
        
        output.company = await vehicles.getCompany({
            transaction
        });
        
        
        output.current_driver = await vehicles.getCurrent_driver({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userCompanies = (user && user.companies?.id) || null;
        

        
        if (userCompanies) {
            if (options?.currentUser?.companiesId) {
                where.companiesId = options.currentUser.companiesId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

      {
        model: db.companies,
        as: 'company',
        
      },

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



    ];

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

            
            if (filter.vehicle_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicles',
                        'vehicle_code',
                        filter.vehicle_code,
                    ),
                };
            }
            
            if (filter.plate_no) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicles',
                        'plate_no',
                        filter.plate_no,
                    ),
                };
            }
            
            if (filter.engine_no) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicles',
                        'engine_no',
                        filter.engine_no,
                    ),
                };
            }
            
            if (filter.chassis_no) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicles',
                        'chassis_no',
                        filter.chassis_no,
                    ),
                };
            }
            
            if (filter.make) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicles',
                        'make',
                        filter.make,
                    ),
                };
            }
            
            if (filter.model) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicles',
                        'model',
                        filter.model,
                    ),
                };
            }
            
            if (filter.colour) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicles',
                        'colour',
                        filter.colour,
                    ),
                };
            }
            
            if (filter.category) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicles',
                        'category',
                        filter.category,
                    ),
                };
            }
            
            if (filter.branch) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicles',
                        'branch',
                        filter.branch,
                    ),
                };
            }
            
            if (filter.insurance_policy_no) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicles',
                        'insurance_policy_no',
                        filter.insurance_policy_no,
                    ),
                };
            }
            
            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.purchase_dateRange) {
                const [start, end] = filter.purchase_dateRange;

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

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

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

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

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

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

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

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

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

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

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

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


      
      if (filter.company) {
        const listItems = filter.company.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          companyId: {[Op.or]: listItems}
        };
      }
      

      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.companiesId;
        }
        

        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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'vehicles',
                        'plate_no',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

