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

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

        const vehicle_inspections = await db.vehicle_inspections.create(
            {
                id: data.id || undefined,
        
        type: data.type
        ||
        null
            ,
            
        issuer: data.issuer
        ||
        null
            ,
            
        report_no: data.report_no
        ||
        null
            ,
            
        performed_at: data.performed_at
        ||
        null
            ,
            
        expires_at: data.expires_at
        ||
        null
            ,
            
        passed: data.passed
        ||
        false
        
            ,
            
        odometer_km: data.odometer_km
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return vehicle_inspections;
    }
    

    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_inspectionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                type: item.type
            ||
            null
            ,
            
                issuer: item.issuer
            ||
            null
            ,
            
                report_no: item.report_no
            ||
            null
            ,
            
                performed_at: item.performed_at
            ||
            null
            ,
            
                expires_at: item.expires_at
            ||
            null
            ,
            
                passed: item.passed
            ||
            false
        
            ,
            
                odometer_km: item.odometer_km
            ||
            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 vehicle_inspections = await db.vehicle_inspections.bulkCreate(vehicle_inspectionsData, { transaction });

        // For each item created, replace relation files
        

        return vehicle_inspections;
    }

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

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


        

        const updatePayload = {};
        
        if (data.type !== undefined) updatePayload.type = data.type;
        
        
        if (data.issuer !== undefined) updatePayload.issuer = data.issuer;
        
        
        if (data.report_no !== undefined) updatePayload.report_no = data.report_no;
        
        
        if (data.performed_at !== undefined) updatePayload.performed_at = data.performed_at;
        
        
        if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
        
        
        if (data.passed !== undefined) updatePayload.passed = data.passed;
        
        
        if (data.odometer_km !== undefined) updatePayload.odometer_km = data.odometer_km;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return vehicle_inspections;
    }

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

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

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


        return vehicle_inspections;
    }

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

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

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

        await vehicle_inspections.destroy({
            transaction
        });

        return vehicle_inspections;
    }

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

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

        if (!vehicle_inspections) {
            return vehicle_inspections;
        }

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

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

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



    ];

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

            
            if (filter.issuer) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicle_inspections',
                        'issuer',
                        filter.issuer,
                    ),
                };
            }
            
            if (filter.report_no) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicle_inspections',
                        'report_no',
                        filter.report_no,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicle_inspections',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            performed_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    expires_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    odometer_km: {
                    ...where.odometer_km,
                            [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.passed) {
                where = {
                    ...where,
                passed: filter.passed,
            };
            }
            


      

      

      



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

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

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

    
};

