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

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

        const ledger_entries = await db.ledger_entries.create(
            {
                id: data.id || undefined,
        
        entry_no: data.entry_no
        ||
        null
            ,
            
        transaction_date: data.transaction_date
        ||
        null
            ,
            
        source_module: data.source_module
        ||
        null
            ,
            
        source_ref: data.source_ref
        ||
        null
            ,
            
        debit: data.debit
        ||
        null
            ,
            
        credit: data.credit
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        created_on: data.created_on
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await ledger_entries.setCompany( data.company || null, {
            transaction,
        });
        
        await ledger_entries.setAccount( data.account || null, {
            transaction,
        });
        
        await ledger_entries.setDriver( data.driver || null, {
            transaction,
        });
        
        await ledger_entries.setVehicle( data.vehicle || null, {
            transaction,
        });
        
        await ledger_entries.setInvoice( data.invoice || null, {
            transaction,
        });
        
        await ledger_entries.setPayment( data.payment || null, {
            transaction,
        });
        
        await ledger_entries.setVehicle_expense( data.vehicle_expense || null, {
            transaction,
        });
        
        await ledger_entries.setBill( data.bill || null, {
            transaction,
        });
        
        await ledger_entries.setReversal_entry( data.reversal_entry || null, {
            transaction,
        });
        

        

        

        return ledger_entries;
    }
    

    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 ledger_entriesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                entry_no: item.entry_no
            ||
            null
            ,
            
                transaction_date: item.transaction_date
            ||
            null
            ,
            
                source_module: item.source_module
            ||
            null
            ,
            
                source_ref: item.source_ref
            ||
            null
            ,
            
                debit: item.debit
            ||
            null
            ,
            
                credit: item.credit
            ||
            null
            ,
            
                description: item.description
            ||
            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 ledger_entries = await db.ledger_entries.bulkCreate(ledger_entriesData, { transaction });

        // For each item created, replace relation files
        

        return ledger_entries;
    }

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


        

        const updatePayload = {};
        
        if (data.entry_no !== undefined) updatePayload.entry_no = data.entry_no;
        
        
        if (data.transaction_date !== undefined) updatePayload.transaction_date = data.transaction_date;
        
        
        if (data.source_module !== undefined) updatePayload.source_module = data.source_module;
        
        
        if (data.source_ref !== undefined) updatePayload.source_ref = data.source_ref;
        
        
        if (data.debit !== undefined) updatePayload.debit = data.debit;
        
        
        if (data.credit !== undefined) updatePayload.credit = data.credit;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.created_on !== undefined) updatePayload.created_on = data.created_on;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.company !== undefined) {
            await ledger_entries.setCompany(
              
              data.company,
              
              { transaction }
            );
        }
        
        if (data.account !== undefined) {
            await ledger_entries.setAccount(
              
              data.account,
              
              { transaction }
            );
        }
        
        if (data.driver !== undefined) {
            await ledger_entries.setDriver(
              
              data.driver,
              
              { transaction }
            );
        }
        
        if (data.vehicle !== undefined) {
            await ledger_entries.setVehicle(
              
              data.vehicle,
              
              { transaction }
            );
        }
        
        if (data.invoice !== undefined) {
            await ledger_entries.setInvoice(
              
              data.invoice,
              
              { transaction }
            );
        }
        
        if (data.payment !== undefined) {
            await ledger_entries.setPayment(
              
              data.payment,
              
              { transaction }
            );
        }
        
        if (data.vehicle_expense !== undefined) {
            await ledger_entries.setVehicle_expense(
              
              data.vehicle_expense,
              
              { transaction }
            );
        }
        
        if (data.bill !== undefined) {
            await ledger_entries.setBill(
              
              data.bill,
              
              { transaction }
            );
        }
        
        if (data.reversal_entry !== undefined) {
            await ledger_entries.setReversal_entry(
              
              data.reversal_entry,
              
              { transaction }
            );
        }
        

        
        

        

        return ledger_entries;
    }

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

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

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


        return ledger_entries;
    }

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

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

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

        await ledger_entries.destroy({
            transaction
        });

        return ledger_entries;
    }

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

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

        if (!ledger_entries) {
            return ledger_entries;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.company = await ledger_entries.getCompany({
            transaction
        });
        
        
        output.account = await ledger_entries.getAccount({
            transaction
        });
        
        
        output.driver = await ledger_entries.getDriver({
            transaction
        });
        
        
        output.vehicle = await ledger_entries.getVehicle({
            transaction
        });
        
        
        output.invoice = await ledger_entries.getInvoice({
            transaction
        });
        
        
        output.payment = await ledger_entries.getPayment({
            transaction
        });
        
        
        output.vehicle_expense = await ledger_entries.getVehicle_expense({
            transaction
        });
        
        
        output.bill = await ledger_entries.getBill({
            transaction
        });
        
        
        output.reversal_entry = await ledger_entries.getReversal_entry({
            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.chart_of_accounts,
        as: 'account',
        
        where: filter.account ? {
          [Op.or]: [
            { id: { [Op.in]: filter.account.split('|').map(term => Utils.uuid(term)) } },
            {
              account_name: {
                [Op.or]: filter.account.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        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.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.payments,
        as: 'payment',
        
        where: filter.payment ? {
          [Op.or]: [
            { id: { [Op.in]: filter.payment.split('|').map(term => Utils.uuid(term)) } },
            {
              payment_ref: {
                [Op.or]: filter.payment.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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



    ];

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

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

            
            

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

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

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

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

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

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

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


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

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

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

    
};

