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

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

        const transactions = await db.transactions.create(
            {
                id: data.id || undefined,
        
        posted_at: data.posted_at
        ||
        null
            ,
            
        effective_at: data.effective_at
        ||
        null
            ,
            
        amount: data.amount
        ||
        null
            ,
            
        currency: data.currency
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        merchant_name: data.merchant_name
        ||
        null
            ,
            
        direction: data.direction
        ||
        null
            ,
            
        category: data.category
        ||
        null
            ,
            
        classification_status: data.classification_status
        ||
        null
            ,
            
        external_reference: data.external_reference
        ||
        null
            ,
            
        is_recurring_candidate: data.is_recurring_candidate
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await transactions.setWorkspace( data.workspace || null, {
            transaction,
        });
        
        await transactions.setFinancial_account( data.financial_account || null, {
            transaction,
        });
        
        await transactions.setData_connection( data.data_connection || null, {
            transaction,
        });
        
        await transactions.setVendor( data.vendor || null, {
            transaction,
        });
        
        await transactions.setCustomer( data.customer || null, {
            transaction,
        });
        
        await transactions.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return 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 transactionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                posted_at: item.posted_at
            ||
            null
            ,
            
                effective_at: item.effective_at
            ||
            null
            ,
            
                amount: item.amount
            ||
            null
            ,
            
                currency: item.currency
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                merchant_name: item.merchant_name
            ||
            null
            ,
            
                direction: item.direction
            ||
            null
            ,
            
                category: item.category
            ||
            null
            ,
            
                classification_status: item.classification_status
            ||
            null
            ,
            
                external_reference: item.external_reference
            ||
            null
            ,
            
                is_recurring_candidate: item.is_recurring_candidate
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

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


        

        const updatePayload = {};
        
        if (data.posted_at !== undefined) updatePayload.posted_at = data.posted_at;
        
        
        if (data.effective_at !== undefined) updatePayload.effective_at = data.effective_at;
        
        
        if (data.amount !== undefined) updatePayload.amount = data.amount;
        
        
        if (data.currency !== undefined) updatePayload.currency = data.currency;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.merchant_name !== undefined) updatePayload.merchant_name = data.merchant_name;
        
        
        if (data.direction !== undefined) updatePayload.direction = data.direction;
        
        
        if (data.category !== undefined) updatePayload.category = data.category;
        
        
        if (data.classification_status !== undefined) updatePayload.classification_status = data.classification_status;
        
        
        if (data.external_reference !== undefined) updatePayload.external_reference = data.external_reference;
        
        
        if (data.is_recurring_candidate !== undefined) updatePayload.is_recurring_candidate = data.is_recurring_candidate;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.workspace !== undefined) {
            await transactions.setWorkspace(
              
              data.workspace,
              
              { transaction }
            );
        }
        
        if (data.financial_account !== undefined) {
            await transactions.setFinancial_account(
              
              data.financial_account,
              
              { transaction }
            );
        }
        
        if (data.data_connection !== undefined) {
            await transactions.setData_connection(
              
              data.data_connection,
              
              { transaction }
            );
        }
        
        if (data.vendor !== undefined) {
            await transactions.setVendor(
              
              data.vendor,
              
              { transaction }
            );
        }
        
        if (data.customer !== undefined) {
            await transactions.setCustomer(
              
              data.customer,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await transactions.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return transactions;
    }

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

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

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


        return transactions;
    }

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

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

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

        await transactions.destroy({
            transaction
        });

        return transactions;
    }

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

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

        if (!transactions) {
            return transactions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.anomalies_transaction = await transactions.getAnomalies_transaction({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.workspace = await transactions.getWorkspace({
            transaction
        });
        
        
        output.financial_account = await transactions.getFinancial_account({
            transaction
        });
        
        
        output.data_connection = await transactions.getData_connection({
            transaction
        });
        
        
        output.vendor = await transactions.getVendor({
            transaction
        });
        
        
        output.customer = await transactions.getCustomer({
            transaction
        });
        
        
        output.organizations = await transactions.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.workspaces,
        as: 'workspace',
        
        where: filter.workspace ? {
          [Op.or]: [
            { id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.workspace.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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

      {
        model: db.customers,
        as: 'customer',
        
        where: filter.customer ? {
          [Op.or]: [
            { id: { [Op.in]: filter.customer.split('|').map(term => Utils.uuid(term)) } },
            {
              customer_name: {
                [Op.or]: filter.customer.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.currency) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'transactions',
                        'currency',
                        filter.currency,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'transactions',
                        'description',
                        filter.description,
                    ),
                };
            }
            
            if (filter.merchant_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'transactions',
                        'merchant_name',
                        filter.merchant_name,
                    ),
                };
            }
            
            if (filter.external_reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'transactions',
                        'external_reference',
                        filter.external_reference,
                    ),
                };
            }
            

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    effective_at: {
                    ...where.effective_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.category) {
                where = {
                    ...where,
                category: filter.category,
            };
            }
            
            if (filter.classification_status) {
                where = {
                    ...where,
                classification_status: filter.classification_status,
            };
            }
            
            if (filter.is_recurring_candidate) {
                where = {
                    ...where,
                is_recurring_candidate: filter.is_recurring_candidate,
            };
            }
            


      

      

      

      

      

      
      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.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(
                        'transactions',
                        'merchant_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

