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

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

        const trailers = await db.trailers.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
            ,
            
        year: data.year
        ||
        null
            ,
            
        first_registration_at: data.first_registration_at
        ||
        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
        
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

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

        return trailers;
    }
    

    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 trailersData = 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
            ,
            
                year: item.year
            ||
            null
            ,
            
                first_registration_at: item.first_registration_at
            ||
            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
        
            ,
            
                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 trailers = await db.trailers.bulkCreate(trailersData, { transaction });

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

        return trailers;
    }

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

        const trailers = await db.trailers.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.year !== undefined) updatePayload.year = data.year;
        
        
        if (data.first_registration_at !== undefined) updatePayload.first_registration_at = data.first_registration_at;
        
        
        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.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

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

        return trailers;
    }

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

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

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


        return trailers;
    }

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

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

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

        await trailers.destroy({
            transaction
        });

        return trailers;
    }

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

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

        if (!trailers) {
            return trailers;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.vehicle_trailer_links_trailer = await trailers.getVehicle_trailer_links_trailer({
            transaction
        });
        
        
        output.vehicle_inspections_trailer = await trailers.getVehicle_inspections_trailer({
            transaction
        });
        
        
        output.vehicle_maintenances_trailer = await trailers.getVehicle_maintenances_trailer({
            transaction
        });
        
        
        output.vehicle_insurances_trailer = await trailers.getVehicle_insurances_trailer({
            transaction
        });
        
        
        output.vehicle_documents_trailer = await trailers.getVehicle_documents_trailer({
            transaction
        });
        
        
        
        
        
        
        
        output.trips_trailer = await trailers.getTrips_trailer({
            transaction
        });
        
        
        
        
        
        
        
        output.cost_items_trailer = await trailers.getCost_items_trailer({
            transaction
        });
        
        
        
        
        
        
        output.company = await trailers.getCompany({
            transaction
        });
        
        
        output.photo = await trailers.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(
                        'trailers',
                        'plate_number',
                        filter.plate_number,
                    ),
                };
            }
            
            if (filter.vin) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'trailers',
                        'vin',
                        filter.vin,
                    ),
                };
            }
            
            if (filter.brand) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'trailers',
                        'brand',
                        filter.brand,
                    ),
                };
            }
            
            if (filter.model) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'trailers',
                        'model',
                        filter.model,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'trailers',
                        '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.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.has_liftgate) {
                where = {
                    ...where,
                has_liftgate: filter.has_liftgate,
            };
            }
            


      



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

        const records = await db.trailers.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,
        }));
    }

    
};

