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

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

        const vehicle_expenses = await db.vehicle_expenses.create(
            {
                id: data.id || undefined,
        
        expense_no: data.expense_no
        ||
        null
            ,
            
        date: data.date
        ||
        null
            ,
            
        expense_category: data.expense_category
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        amount: data.amount
        ||
        null
            ,
            
        tax_amount: data.tax_amount
        ||
        null
            ,
            
        gross_amount: data.gross_amount
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        created_on: data.created_on
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await vehicle_expenses.setCompany( data.company || null, {
            transaction,
        });
        
        await vehicle_expenses.setVehicle( data.vehicle || null, {
            transaction,
        });
        
        await vehicle_expenses.setVendor( data.vendor || null, {
            transaction,
        });
        
        await vehicle_expenses.setExpense_account( data.expense_account || null, {
            transaction,
        });
        
        await vehicle_expenses.setPayment_account( data.payment_account || null, {
            transaction,
        });
        

        

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

        return vehicle_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 vehicle_expensesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                expense_no: item.expense_no
            ||
            null
            ,
            
                date: item.date
            ||
            null
            ,
            
                expense_category: item.expense_category
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                amount: item.amount
            ||
            null
            ,
            
                tax_amount: item.tax_amount
            ||
            null
            ,
            
                gross_amount: item.gross_amount
            ||
            null
            ,
            
                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 vehicle_expenses = await db.vehicle_expenses.bulkCreate(vehicle_expensesData, { transaction });

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

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


        

        const updatePayload = {};
        
        if (data.expense_no !== undefined) updatePayload.expense_no = data.expense_no;
        
        
        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.tax_amount !== undefined) updatePayload.tax_amount = data.tax_amount;
        
        
        if (data.gross_amount !== undefined) updatePayload.gross_amount = data.gross_amount;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.created_on !== undefined) updatePayload.created_on = data.created_on;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await vehicle_expenses.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        
        if (data.vehicle !== undefined) {
            await vehicle_expenses.setVehicle(
              
              data.vehicle,
              
              { transaction }
            );
        }
        
        if (data.vendor !== undefined) {
            await vehicle_expenses.setVendor(
              
              data.vendor,
              
              { transaction }
            );
        }
        
        if (data.expense_account !== undefined) {
            await vehicle_expenses.setExpense_account(
              
              data.expense_account,
              
              { transaction }
            );
        }
        
        if (data.payment_account !== undefined) {
            await vehicle_expenses.setPayment_account(
              
              data.payment_account,
              
              { transaction }
            );
        }
        

        
        

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

        return vehicle_expenses;
    }

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

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

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


        return vehicle_expenses;
    }

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

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

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

        await vehicle_expenses.destroy({
            transaction
        });

        return vehicle_expenses;
    }

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

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

        if (!vehicle_expenses) {
            return vehicle_expenses;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.ledger_entries_vehicle_expense = await vehicle_expenses.getLedger_entries_vehicle_expense({
            transaction
        });
        
        
        
        
        
        
        
        output.company = await vehicle_expenses.getCompany({
            transaction
        });
        
        
        output.vehicle = await vehicle_expenses.getVehicle({
            transaction
        });
        
        
        output.vendor = await vehicle_expenses.getVendor({
            transaction
        });
        
        
        output.expense_account = await vehicle_expenses.getExpense_account({
            transaction
        });
        
        
        output.payment_account = await vehicle_expenses.getPayment_account({
            transaction
        });
        
        
        output.attachment = await vehicle_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.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.vendors,
        as: 'vendor',
        
        where: filter.vendor ? {
          [Op.or]: [
            { id: { [Op.in]: filter.vendor.split('|').map(term => Utils.uuid(term)) } },
            {
              vendor_name: {
                [Op.or]: filter.vendor.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_no) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicle_expenses',
                        'expense_no',
                        filter.expense_no,
                    ),
                };
            }
            
            if (filter.expense_category) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicle_expenses',
                        'expense_category',
                        filter.expense_category,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vehicle_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.tax_amountRange) {
                const [start, end] = filter.tax_amountRange;

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    gross_amount: {
                    ...where.gross_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.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.vehicle_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(
                        'vehicle_expenses',
                        'expense_no',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

