
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const { resolveCurrencyId } = require('./defaultCurrency');



const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class Bank_transactionsDBApi {
    

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

        const bank_transactions = await db.bank_transactions.create(
            {
                id: data.id || undefined,
        
        transaction_date: data.transaction_date
        ||
        null
            ,
            
        posted_at: data.posted_at
        ||
        null
            ,
            
        direction: data.direction
        ||
        null
            ,
            
        amount: data.amount
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        reference: data.reference
        ||
        null
            ,
            
        match_status: data.match_status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await bank_transactions.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await bank_transactions.setBank_account( data.bank_account || null, {
            transaction,
        });
        const currencyId = await resolveCurrencyId(db, data.currency, transaction);
        await bank_transactions.setCurrency(currencyId, {
            transaction,
        });
        

        

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

        return bank_transactions;
    }
    

    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 bank_transactionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                transaction_date: item.transaction_date
            ||
            null
            ,
            
                posted_at: item.posted_at
            ||
            null
            ,
            
                direction: item.direction
            ||
            null
            ,
            
                amount: item.amount
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                reference: item.reference
            ||
            null
            ,
            
                match_status: item.match_status
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < bank_transactions.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.bank_transactions.getTableName(),
                    belongsToColumn: 'import_source_file',
                    belongsToId: bank_transactions[i].id,
                },
                data[i].import_source_file,
                options,
            );
        }
        

        return bank_transactions;
    }

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


        

        const updatePayload = {};
        
        if (data.transaction_date !== undefined) updatePayload.transaction_date = data.transaction_date;
        
        
        if (data.posted_at !== undefined) updatePayload.posted_at = data.posted_at;
        
        
        if (data.direction !== undefined) updatePayload.direction = data.direction;
        
        
        if (data.amount !== undefined) updatePayload.amount = data.amount;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.reference !== undefined) updatePayload.reference = data.reference;
        
        
        if (data.match_status !== undefined) updatePayload.match_status = data.match_status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await bank_transactions.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.bank_account !== undefined) {
            await bank_transactions.setBank_account(
              
              data.bank_account,
              
              { transaction }
            );
        }
        
        if (data.currency !== undefined) {
            await bank_transactions.setCurrency(
              
              data.currency,
              
              { transaction }
            );
        }
        

        
        

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

        return bank_transactions;
    }

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

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

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


        return bank_transactions;
    }

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

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

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

        await bank_transactions.destroy({
            transaction
        });

        return bank_transactions;
    }

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

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

        if (!bank_transactions) {
            return bank_transactions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.journal_entries_source_bank_transaction = await bank_transactions.getJournal_entries_source_bank_transaction({
            transaction
        });
        
        
        
        
        
        
        output.organization = await bank_transactions.getOrganization({
            transaction
        });
        
        
        output.bank_account = await bank_transactions.getBank_account({
            transaction
        });
        
        
        output.currency = await bank_transactions.getCurrency({
            transaction
        });
        
        
        output.import_source_file = await bank_transactions.getImport_source_file({
            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_accounts,
        as: 'bank_account',
        
        where: filter.bank_account ? {
          [Op.or]: [
            { id: { [Op.in]: filter.bank_account.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.bank_account.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



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

    ];

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

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

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            transaction_date: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    posted_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    amount: {
                    ...where.amount,
                            [Op.lte]: end,
                    },
                };
                }
            }
            

            if (filter.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            
            if (filter.direction) {
                where = {
                    ...where,
                direction: filter.direction,
            };
            }
            
            if (filter.match_status) {
                where = {
                    ...where,
                match_status: filter.match_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.bank_transactions.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(
                        'bank_transactions',
                        'reference',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

