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

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

        const driver_profiles = await db.driver_profiles.create(
            {
                id: data.id || undefined,
        
        driver_notes: data.driver_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await driver_profiles.setEmployee( data.employee || null, {
            transaction,
        });
        
        await driver_profiles.setCompliance( data.compliance || null, {
            transaction,
        });
        

        

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

        return driver_profiles;
    }
    

    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 driver_profilesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                driver_notes: item.driver_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return driver_profiles;
    }

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

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


        

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

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

        
        
        if (data.employee !== undefined) {
            await driver_profiles.setEmployee(
              
              data.employee,
              
              { transaction }
            );
        }
        
        if (data.compliance !== undefined) {
            await driver_profiles.setCompliance(
              
              data.compliance,
              
              { transaction }
            );
        }
        

        
        

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

        return driver_profiles;
    }

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

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

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


        return driver_profiles;
    }

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

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

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

        await driver_profiles.destroy({
            transaction
        });

        return driver_profiles;
    }

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

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

        if (!driver_profiles) {
            return driver_profiles;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.driver_compliances_driver_profile = await driver_profiles.getDriver_compliances_driver_profile({
            transaction
        });
        
        
        output.incidents_driver_profile = await driver_profiles.getIncidents_driver_profile({
            transaction
        });
        
        
        output.documents_driver_profile = await driver_profiles.getDocuments_driver_profile({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.employee = await driver_profiles.getEmployee({
            transaction
        });
        
        
        output.photo = await driver_profiles.getPhoto({
            transaction
        });
        
        
        output.compliance = await driver_profiles.getCompliance({
            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.employees,
        as: 'employee',
        
        where: filter.employee ? {
          [Op.or]: [
            { id: { [Op.in]: filter.employee.split('|').map(term => Utils.uuid(term)) } },
            {
              last_name: {
                [Op.or]: filter.employee.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.driver_compliances,
        as: 'compliance',
        
        where: filter.compliance ? {
          [Op.or]: [
            { id: { [Op.in]: filter.compliance.split('|').map(term => Utils.uuid(term)) } },
            {
              license_number: {
                [Op.or]: filter.compliance.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.driver_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'driver_profiles',
                        'driver_notes',
                        filter.driver_notes,
                    ),
                };
            }
            

            
            

            

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

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

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

    
};

