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

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

        const journal_entries = await db.journal_entries.create(
            {
                id: data.id || undefined,
        
        journal_number: data.journal_number
        ||
        null
            ,
            
        date: data.date
        ||
        null
            ,
            
        entries: data.entries
        ||
        null
            ,
            
        total_debit: data.total_debit
        ||
        null
            ,
            
        total_credit: data.total_credit
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return journal_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 journal_entriesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                journal_number: item.journal_number
            ||
            null
            ,
            
                date: item.date
            ||
            null
            ,
            
                entries: item.entries
            ||
            null
            ,
            
                total_debit: item.total_debit
            ||
            null
            ,
            
                total_credit: item.total_credit
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return journal_entries;
    }

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

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


        

        const updatePayload = {};
        
        if (data.journal_number !== undefined) updatePayload.journal_number = data.journal_number;
        
        
        if (data.date !== undefined) updatePayload.date = data.date;
        
        
        if (data.entries !== undefined) updatePayload.entries = data.entries;
        
        
        if (data.total_debit !== undefined) updatePayload.total_debit = data.total_debit;
        
        
        if (data.total_credit !== undefined) updatePayload.total_credit = data.total_credit;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return journal_entries;
    }

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

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

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


        return journal_entries;
    }

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

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

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

        await journal_entries.destroy({
            transaction
        });

        return journal_entries;
    }

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

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

        if (!journal_entries) {
            return journal_entries;
        }

        const output = journal_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.journal_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'journal_entries',
                        'journal_number',
                        filter.journal_number,
                    ),
                };
            }
            
            if (filter.entries) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'journal_entries',
                        'entries',
                        filter.entries,
                    ),
                };
            }
            

            
            

            
            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.total_debitRange) {
                const [start, end] = filter.total_debitRange;

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    total_credit: {
                    ...where.total_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.journal_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(
                        'journal_entries',
                        'journal_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

