
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_number: data.entry_number
        ||
        null
            ,
            
        date: data.date
        ||
        null
            ,
            
        account: data.account
        ||
        null
            ,
            
        debit: data.debit
        ||
        null
            ,
            
        credit: data.credit
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { 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_number: item.entry_number
            ||
            null
            ,
            
                date: item.date
            ||
            null
            ,
            
                account: item.account
            ||
            null
            ,
            
                debit: item.debit
            ||
            null
            ,
            
                credit: item.credit
            ||
            null
            ,
            
                description: item.description
            ||
            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 ledger_entries = await db.ledger_entries.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.entry_number !== undefined) updatePayload.entry_number = data.entry_number;
        
        
        if (data.date !== undefined) updatePayload.date = data.date;
        
        
        if (data.account !== undefined) updatePayload.account = data.account;
        
        
        if (data.debit !== undefined) updatePayload.debit = data.debit;
        
        
        if (data.credit !== undefined) updatePayload.credit = data.credit;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        updatePayload.updatedById = currentUser.id;

        await ledger_entries.update(updatePayload, {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});

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        

        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 = [



    ];

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

            
            if (filter.entry_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ledger_entries',
                        'entry_number',
                        filter.entry_number,
                    ),
                };
            }
            
            if (filter.account) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ledger_entries',
                        'account',
                        filter.account,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ledger_entries',
                        '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.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.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.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, ) {
        let where = {};
        
        

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

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

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

    
};

