
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,
        
        entry_number: data.entry_number
        ||
        null
            ,
            
        entry_date: data.entry_date
        ||
        null
            ,
            
        source_module: data.source_module
        ||
        null
            ,
            
        reference: data.reference
        ||
        null
            ,
            
        total_debit: data.total_debit
        ||
        null
            ,
            
        total_credit: data.total_credit
        ||
        null
            ,
            
        posted_at: data.posted_at
        ||
        null
            ,
            
        memo: data.memo
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await journal_entries.setBranch( data.branch || null, {
            transaction,
        });
        
        await journal_entries.setPosted_by( data.posted_by || null, {
            transaction,
        });
        
        await journal_entries.setOrganizations( data.organizations || null, {
            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,
                
                entry_number: item.entry_number
            ||
            null
            ,
            
                entry_date: item.entry_date
            ||
            null
            ,
            
                source_module: item.source_module
            ||
            null
            ,
            
                reference: item.reference
            ||
            null
            ,
            
                total_debit: item.total_debit
            ||
            null
            ,
            
                total_credit: item.total_credit
            ||
            null
            ,
            
                posted_at: item.posted_at
            ||
            null
            ,
            
                memo: item.memo
            ||
            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 globalAccess = currentUser.app_role?.globalAccess;

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


        

        const updatePayload = {};
        
        if (data.entry_number !== undefined) updatePayload.entry_number = data.entry_number;
        
        
        if (data.entry_date !== undefined) updatePayload.entry_date = data.entry_date;
        
        
        if (data.source_module !== undefined) updatePayload.source_module = data.source_module;
        
        
        if (data.reference !== undefined) updatePayload.reference = data.reference;
        
        
        if (data.total_debit !== undefined) updatePayload.total_debit = data.total_debit;
        
        
        if (data.total_credit !== undefined) updatePayload.total_credit = data.total_credit;
        
        
        if (data.posted_at !== undefined) updatePayload.posted_at = data.posted_at;
        
        
        if (data.memo !== undefined) updatePayload.memo = data.memo;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.branch !== undefined) {
            await journal_entries.setBranch(
              
              data.branch,
              
              { transaction }
            );
        }
        
        if (data.posted_by !== undefined) {
            await journal_entries.setPosted_by(
              
              data.posted_by,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await journal_entries.setOrganizations(
              
              data.organizations,
              
              { 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});

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.journal_lines_journal_entry = await journal_entries.getJournal_lines_journal_entry({
            transaction
        });
        
        
        
        
        
        
        
        
        output.branch = await journal_entries.getBranch({
            transaction
        });
        
        
        output.posted_by = await journal_entries.getPosted_by({
            transaction
        });
        
        
        output.organizations = await journal_entries.getOrganizations({
            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 userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



    ];

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

            
            if (filter.entry_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'journal_entries',
                        'entry_number',
                        filter.entry_number,
                    ),
                };
            }
            
            if (filter.reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'journal_entries',
                        'reference',
                        filter.reference,
                    ),
                };
            }
            
            if (filter.memo) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'journal_entries',
                        'memo',
                        filter.memo,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    entry_date: {
                    ...where.entry_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.posted_atRange) {
                const [start, end] = filter.posted_atRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    posted_at: {
                    ...where.posted_at,
                            [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.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[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.organizationsId;
        }
        

        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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

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

        const records = await db.journal_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,
        }));
    }

    
};

