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

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

        const vehicle_compliance = await db.vehicle_compliance.create(
            {
                id: data.id || undefined,
        
        registration_expiry: data.registration_expiry
        ||
        null
            ,
            
        fitness_expiry: data.fitness_expiry
        ||
        null
            ,
            
        insurance_expiry: data.insurance_expiry
        ||
        null
            ,
            
        insurance_policy_no: data.insurance_policy_no
        ||
        null
            ,
            
        certificate_no: data.certificate_no
        ||
        null
            ,
            
        mileage: data.mileage
        ||
        null
            ,
            
        registration_status: data.registration_status
        ||
        null
            ,
            
        insurance_status: data.insurance_status
        ||
        null
            ,
            
        fitness_status: data.fitness_status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await vehicle_compliance.setCompany( data.company || null, {
            transaction,
        });
        
        await vehicle_compliance.setVehicle( data.vehicle || null, {
            transaction,
        });
        

        

        

        return vehicle_compliance;
    }
    

    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 vehicle_complianceData = data.map((item, index) => ({
                id: item.id || undefined,
                
                registration_expiry: item.registration_expiry
            ||
            null
            ,
            
                fitness_expiry: item.fitness_expiry
            ||
            null
            ,
            
                insurance_expiry: item.insurance_expiry
            ||
            null
            ,
            
                insurance_policy_no: item.insurance_policy_no
            ||
            null
            ,
            
                certificate_no: item.certificate_no
            ||
            null
            ,
            
                mileage: item.mileage
            ||
            null
            ,
            
                registration_status: item.registration_status
            ||
            null
            ,
            
                insurance_status: item.insurance_status
            ||
            null
            ,
            
                fitness_status: item.fitness_status
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return vehicle_compliance;
    }

    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 vehicle_compliance = await db.vehicle_compliance.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.registration_expiry !== undefined) updatePayload.registration_expiry = data.registration_expiry;
        
        
        if (data.fitness_expiry !== undefined) updatePayload.fitness_expiry = data.fitness_expiry;
        
        
        if (data.insurance_expiry !== undefined) updatePayload.insurance_expiry = data.insurance_expiry;
        
        
        if (data.insurance_policy_no !== undefined) updatePayload.insurance_policy_no = data.insurance_policy_no;
        
        
        if (data.certificate_no !== undefined) updatePayload.certificate_no = data.certificate_no;
        
        
        if (data.mileage !== undefined) updatePayload.mileage = data.mileage;
        
        
        if (data.registration_status !== undefined) updatePayload.registration_status = data.registration_status;
        
        
        if (data.insurance_status !== undefined) updatePayload.insurance_status = data.insurance_status;
        
        
        if (data.fitness_status !== undefined) updatePayload.fitness_status = data.fitness_status;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return vehicle_compliance;
    }

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

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

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


        return vehicle_compliance;
    }

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

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

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

        await vehicle_compliance.destroy({
            transaction
        });

        return vehicle_compliance;
    }

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

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

        if (!vehicle_compliance) {
            return vehicle_compliance;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.company = await vehicle_compliance.getCompany({
            transaction
        });
        
        
        output.vehicle = await vehicle_compliance.getVehicle({
            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.vehicles,
        as: 'vehicle',
        
        where: filter.vehicle ? {
          [Op.or]: [
            { id: { [Op.in]: filter.vehicle.split('|').map(term => Utils.uuid(term)) } },
            {
              plate_no: {
                [Op.or]: filter.vehicle.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.insurance_policy_no) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicle_compliance',
                        'insurance_policy_no',
                        filter.insurance_policy_no,
                    ),
                };
            }
            
            if (filter.certificate_no) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicle_compliance',
                        'certificate_no',
                        filter.certificate_no,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

            
            if (filter.registration_status) {
                where = {
                    ...where,
                registration_status: filter.registration_status,
            };
            }
            
            if (filter.insurance_status) {
                where = {
                    ...where,
                insurance_status: filter.insurance_status,
            };
            }
            
            if (filter.fitness_status) {
                where = {
                    ...where,
                fitness_status: filter.fitness_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.vehicle_compliance.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(
                        'vehicle_compliance',
                        'certificate_no',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

