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

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

        const vehicle_trailer_links = await db.vehicle_trailer_links.create(
            {
                id: data.id || undefined,
        
        linked_from: data.linked_from
        ||
        null
            ,
            
        linked_to: data.linked_to
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return vehicle_trailer_links;
    }
    

    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_trailer_linksData = data.map((item, index) => ({
                id: item.id || undefined,
                
                linked_from: item.linked_from
            ||
            null
            ,
            
                linked_to: item.linked_to
            ||
            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_trailer_links = await db.vehicle_trailer_links.bulkCreate(vehicle_trailer_linksData, { transaction });

        // For each item created, replace relation files
        

        return vehicle_trailer_links;
    }

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

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


        

        const updatePayload = {};
        
        if (data.linked_from !== undefined) updatePayload.linked_from = data.linked_from;
        
        
        if (data.linked_to !== undefined) updatePayload.linked_to = data.linked_to;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return vehicle_trailer_links;
    }

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

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

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


        return vehicle_trailer_links;
    }

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

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

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

        await vehicle_trailer_links.destroy({
            transaction
        });

        return vehicle_trailer_links;
    }

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

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

        if (!vehicle_trailer_links) {
            return vehicle_trailer_links;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.company = await vehicle_trailer_links.getCompany({
            transaction
        });
        
        
        output.vehicle = await vehicle_trailer_links.getVehicle({
            transaction
        });
        
        
        output.trailer = await vehicle_trailer_links.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.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicle_trailer_links',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            


      

      

      



            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_trailer_links.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_trailer_links',
                        'notes',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

