
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
            ,
            
        status: data.status
        ||
        null
            ,
            
        memo: data.memo
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await journal_entries.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await journal_entries.setSource_bank_transaction( data.source_bank_transaction || null, {
            transaction,
        });
        

        

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

        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
            ,
            
                status: item.status
            ||
            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
        
        for (let i = 0; i < journal_entries.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.journal_entries.getTableName(),
                    belongsToColumn: 'attachments',
                    belongsToId: journal_entries[i].id,
                },
                data[i].attachments,
                options,
            );
        }
        

        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.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.memo !== undefined) updatePayload.memo = data.memo;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await journal_entries.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.source_bank_transaction !== undefined) {
            await journal_entries.setSource_bank_transaction(
              
              data.source_bank_transaction,
              
              { transaction }
            );
        }
        

        
        

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

        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.organization = await journal_entries.getOrganization({
            transaction
        });
        
        
        output.source_bank_transaction = await journal_entries.getSource_bank_transaction({
            transaction
        });
        
        
        output.attachments = await journal_entries.getAttachments({
            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.organizations,
        as: 'organization',
        
      },

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



      {
        model: db.file,
        as: 'attachments',
      },

    ];

        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.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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


      
      if (filter.organization) {
        const listItems = filter.organization.split('|').map(item => {
          return  Utils.uuid(item)
        });

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

    
};

