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

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

        const driver_expenses = await db.driver_expenses.create(
            {
                id: data.id || undefined,
        
        date: data.date
        ||
        null
            ,
            
        expense_category: data.expense_category
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        amount: data.amount
        ||
        null
            ,
            
        charge_to_driver_flag: data.charge_to_driver_flag
        ||
        false
        
            ,
            
        billable_to_driver_flag: data.billable_to_driver_flag
        ||
        false
        
            ,
            
        status: data.status
        ||
        null
            ,
            
        created_on: data.created_on
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await driver_expenses.setCompany( data.company || null, {
            transaction,
        });
        
        await driver_expenses.setDriver( data.driver || null, {
            transaction,
        });
        
        await driver_expenses.setVehicle( data.vehicle || null, {
            transaction,
        });
        
        await driver_expenses.setAgreement( data.agreement || null, {
            transaction,
        });
        
        await driver_expenses.setInvoice( data.invoice || null, {
            transaction,
        });
        
        await driver_expenses.setExpense_account( data.expense_account || null, {
            transaction,
        });
        
        await driver_expenses.setPayment_account( data.payment_account || null, {
            transaction,
        });
        

        

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

        return driver_expenses;
    }
    

    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_expensesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                date: item.date
            ||
            null
            ,
            
                expense_category: item.expense_category
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                amount: item.amount
            ||
            null
            ,
            
                charge_to_driver_flag: item.charge_to_driver_flag
            ||
            false
        
            ,
            
                billable_to_driver_flag: item.billable_to_driver_flag
            ||
            false
        
            ,
            
                status: item.status
            ||
            null
            ,
            
                created_on: item.created_on
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return driver_expenses;
    }

    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 driver_expenses = await db.driver_expenses.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.date !== undefined) updatePayload.date = data.date;
        
        
        if (data.expense_category !== undefined) updatePayload.expense_category = data.expense_category;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.amount !== undefined) updatePayload.amount = data.amount;
        
        
        if (data.charge_to_driver_flag !== undefined) updatePayload.charge_to_driver_flag = data.charge_to_driver_flag;
        
        
        if (data.billable_to_driver_flag !== undefined) updatePayload.billable_to_driver_flag = data.billable_to_driver_flag;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.created_on !== undefined) updatePayload.created_on = data.created_on;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await driver_expenses.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        
        if (data.driver !== undefined) {
            await driver_expenses.setDriver(
              
              data.driver,
              
              { transaction }
            );
        }
        
        if (data.vehicle !== undefined) {
            await driver_expenses.setVehicle(
              
              data.vehicle,
              
              { transaction }
            );
        }
        
        if (data.agreement !== undefined) {
            await driver_expenses.setAgreement(
              
              data.agreement,
              
              { transaction }
            );
        }
        
        if (data.invoice !== undefined) {
            await driver_expenses.setInvoice(
              
              data.invoice,
              
              { transaction }
            );
        }
        
        if (data.expense_account !== undefined) {
            await driver_expenses.setExpense_account(
              
              data.expense_account,
              
              { transaction }
            );
        }
        
        if (data.payment_account !== undefined) {
            await driver_expenses.setPayment_account(
              
              data.payment_account,
              
              { transaction }
            );
        }
        

        
        

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

        return driver_expenses;
    }

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

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

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


        return driver_expenses;
    }

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

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

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

        await driver_expenses.destroy({
            transaction
        });

        return driver_expenses;
    }

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

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

        if (!driver_expenses) {
            return driver_expenses;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.company = await driver_expenses.getCompany({
            transaction
        });
        
        
        output.driver = await driver_expenses.getDriver({
            transaction
        });
        
        
        output.vehicle = await driver_expenses.getVehicle({
            transaction
        });
        
        
        output.agreement = await driver_expenses.getAgreement({
            transaction
        });
        
        
        output.invoice = await driver_expenses.getInvoice({
            transaction
        });
        
        
        output.expense_account = await driver_expenses.getExpense_account({
            transaction
        });
        
        
        output.payment_account = await driver_expenses.getPayment_account({
            transaction
        });
        
        
        output.attachment = await driver_expenses.getAttachment({
            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',
        
      },

      {
        model: db.drivers,
        as: 'driver',
        
        where: filter.driver ? {
          [Op.or]: [
            { id: { [Op.in]: filter.driver.split('|').map(term => Utils.uuid(term)) } },
            {
              driver_name: {
                [Op.or]: filter.driver.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_no: {
                [Op.or]: filter.vehicle.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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

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



      {
        model: db.file,
        as: 'attachment',
      },

    ];

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

            
            if (filter.expense_category) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'driver_expenses',
                        'expense_category',
                        filter.expense_category,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'driver_expenses',
                        'description',
                        filter.description,
                    ),
                };
            }
            

            
            

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    amount: {
                    ...where.amount,
                            [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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            
            if (filter.charge_to_driver_flag) {
                where = {
                    ...where,
                charge_to_driver_flag: filter.charge_to_driver_flag,
            };
            }
            
            if (filter.billable_to_driver_flag) {
                where = {
                    ...where,
                billable_to_driver_flag: filter.billable_to_driver_flag,
            };
            }
            
            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.driver_expenses.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(
                        'driver_expenses',
                        'expense_category',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

