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

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

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

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

        

        

        return vehicle_documents;
    }
    

    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_documentsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                type: item.type
            ||
            null
            ,
            
                title: item.title
            ||
            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_documents = await db.vehicle_documents.bulkCreate(vehicle_documentsData, { transaction });

        // For each item created, replace relation files
        

        return vehicle_documents;
    }

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

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


        

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

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

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

        
        

        

        return vehicle_documents;
    }

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

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

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


        return vehicle_documents;
    }

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

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

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

        await vehicle_documents.destroy({
            transaction
        });

        return vehicle_documents;
    }

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

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

        if (!vehicle_documents) {
            return vehicle_documents;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.vehicle_document_versions_document = await vehicle_documents.getVehicle_document_versions_document({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.company = await vehicle_documents.getCompany({
            transaction
        });
        
        
        output.vehicle = await vehicle_documents.getVehicle({
            transaction
        });
        
        
        output.trailer = await vehicle_documents.getTrailer({
            transaction
        });
        
        
        output.current_version = await vehicle_documents.getCurrent_version({
            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}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

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

            
            

            

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

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


      

      

      

      



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

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

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

    
};

