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

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

        const drivers = await db.drivers.create(
            {
                id: data.id || undefined,
        
        driver_code: data.driver_code
        ||
        null
            ,
            
        driver_name: data.driver_name
        ||
        null
            ,
            
        phone: data.phone
        ||
        null
            ,
            
        email: data.email
        ||
        null
            ,
            
        address: data.address
        ||
        null
            ,
            
        license_number: data.license_number
        ||
        null
            ,
            
        license_expiry_date: data.license_expiry_date
        ||
        null
            ,
            
        national_id: data.national_id
        ||
        null
            ,
            
        trn_tax_id: data.trn_tax_id
        ||
        null
            ,
            
        security_deposit: data.security_deposit
        ||
        null
            ,
            
        credit_limit: data.credit_limit
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
        created_on: data.created_on
        ||
        null
            ,
            
        modified_on: data.modified_on
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return drivers;
    }
    

    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 driversData = data.map((item, index) => ({
                id: item.id || undefined,
                
                driver_code: item.driver_code
            ||
            null
            ,
            
                driver_name: item.driver_name
            ||
            null
            ,
            
                phone: item.phone
            ||
            null
            ,
            
                email: item.email
            ||
            null
            ,
            
                address: item.address
            ||
            null
            ,
            
                license_number: item.license_number
            ||
            null
            ,
            
                license_expiry_date: item.license_expiry_date
            ||
            null
            ,
            
                national_id: item.national_id
            ||
            null
            ,
            
                trn_tax_id: item.trn_tax_id
            ||
            null
            ,
            
                security_deposit: item.security_deposit
            ||
            null
            ,
            
                credit_limit: item.credit_limit
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
                created_on: item.created_on
            ||
            null
            ,
            
                modified_on: item.modified_on
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return drivers;
    }

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

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


        

        const updatePayload = {};
        
        if (data.driver_code !== undefined) updatePayload.driver_code = data.driver_code;
        
        
        if (data.driver_name !== undefined) updatePayload.driver_name = data.driver_name;
        
        
        if (data.phone !== undefined) updatePayload.phone = data.phone;
        
        
        if (data.email !== undefined) updatePayload.email = data.email;
        
        
        if (data.address !== undefined) updatePayload.address = data.address;
        
        
        if (data.license_number !== undefined) updatePayload.license_number = data.license_number;
        
        
        if (data.license_expiry_date !== undefined) updatePayload.license_expiry_date = data.license_expiry_date;
        
        
        if (data.national_id !== undefined) updatePayload.national_id = data.national_id;
        
        
        if (data.trn_tax_id !== undefined) updatePayload.trn_tax_id = data.trn_tax_id;
        
        
        if (data.security_deposit !== undefined) updatePayload.security_deposit = data.security_deposit;
        
        
        if (data.credit_limit !== undefined) updatePayload.credit_limit = data.credit_limit;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        if (data.created_on !== undefined) updatePayload.created_on = data.created_on;
        
        
        if (data.modified_on !== undefined) updatePayload.modified_on = data.modified_on;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return drivers;
    }

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

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

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


        return drivers;
    }

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

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

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

        await drivers.destroy({
            transaction
        });

        return drivers;
    }

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

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

        if (!drivers) {
            return drivers;
        }

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

        
        
        
        
        
        
        output.vehicles_current_driver = await drivers.getVehicles_current_driver({
            transaction
        });
        
        
        output.agreements_driver = await drivers.getAgreements_driver({
            transaction
        });
        
        
        
        output.invoices_driver = await drivers.getInvoices_driver({
            transaction
        });
        
        
        
        
        output.payments_driver = await drivers.getPayments_driver({
            transaction
        });
        
        
        
        
        
        output.driver_expenses_driver = await drivers.getDriver_expenses_driver({
            transaction
        });
        
        
        
        
        
        output.ledger_entries_driver = await drivers.getLedger_entries_driver({
            transaction
        });
        
        
        
        
        
        
        
        output.company = await drivers.getCompany({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userCompanies = (user && user.companies?.id) || null;
        

        
        if (userCompanies) {
            if (options?.currentUser?.companiesId) {
                where.companiesId = options.currentUser.companiesId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

      {
        model: db.companies,
        as: 'company',
        
      },



    ];

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

            
            if (filter.driver_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'drivers',
                        'driver_code',
                        filter.driver_code,
                    ),
                };
            }
            
            if (filter.driver_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'drivers',
                        'driver_name',
                        filter.driver_name,
                    ),
                };
            }
            
            if (filter.phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'drivers',
                        'phone',
                        filter.phone,
                    ),
                };
            }
            
            if (filter.email) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'drivers',
                        'email',
                        filter.email,
                    ),
                };
            }
            
            if (filter.address) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'drivers',
                        'address',
                        filter.address,
                    ),
                };
            }
            
            if (filter.license_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'drivers',
                        'license_number',
                        filter.license_number,
                    ),
                };
            }
            
            if (filter.national_id) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'drivers',
                        'national_id',
                        filter.national_id,
                    ),
                };
            }
            
            if (filter.trn_tax_id) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'drivers',
                        'trn_tax_id',
                        filter.trn_tax_id,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'drivers',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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


      
      if (filter.company) {
        const listItems = filter.company.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          companyId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.companiesId;
        }
        

        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.drivers.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'drivers',
                        'driver_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

