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

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

        const bank_verifications = await db.bank_verifications.create(
            {
                id: data.id || undefined,
        
        bank_name: data.bank_name
        ||
        null
            ,
            
        account_identifier: data.account_identifier
        ||
        null
            ,
            
        expected_amount: data.expected_amount
        ||
        null
            ,
            
        reported_amount: data.reported_amount
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        verified_at: data.verified_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await bank_verifications.setAuthentication_attempt( data.authentication_attempt || null, {
            transaction,
        });
        
        await bank_verifications.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return bank_verifications;
    }
    

    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_verificationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                bank_name: item.bank_name
            ||
            null
            ,
            
                account_identifier: item.account_identifier
            ||
            null
            ,
            
                expected_amount: item.expected_amount
            ||
            null
            ,
            
                reported_amount: item.reported_amount
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                verified_at: item.verified_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return bank_verifications;
    }

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


        

        const updatePayload = {};
        
        if (data.bank_name !== undefined) updatePayload.bank_name = data.bank_name;
        
        
        if (data.account_identifier !== undefined) updatePayload.account_identifier = data.account_identifier;
        
        
        if (data.expected_amount !== undefined) updatePayload.expected_amount = data.expected_amount;
        
        
        if (data.reported_amount !== undefined) updatePayload.reported_amount = data.reported_amount;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.verified_at !== undefined) updatePayload.verified_at = data.verified_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.authentication_attempt !== undefined) {
            await bank_verifications.setAuthentication_attempt(
              
              data.authentication_attempt,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await bank_verifications.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return bank_verifications;
    }

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

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

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


        return bank_verifications;
    }

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

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

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

        await bank_verifications.destroy({
            transaction
        });

        return bank_verifications;
    }

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

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

        if (!bank_verifications) {
            return bank_verifications;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.authentication_attempt = await bank_verifications.getAuthentication_attempt({
            transaction
        });
        
        
        output.organizations = await bank_verifications.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.authentication_attempts,
        as: 'authentication_attempt',
        
        where: filter.authentication_attempt ? {
          [Op.or]: [
            { id: { [Op.in]: filter.authentication_attempt.split('|').map(term => Utils.uuid(term)) } },
            {
              status: {
                [Op.or]: filter.authentication_attempt.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.bank_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'bank_verifications',
                        'bank_name',
                        filter.bank_name,
                    ),
                };
            }
            
            if (filter.account_identifier) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'bank_verifications',
                        'account_identifier',
                        filter.account_identifier,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    verified_at: {
                    ...where.verified_at,
                            [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.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.bank_verifications.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_verifications',
                        'bank_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

