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

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

        const bank_files = await db.bank_files.create(
            {
                id: data.id || undefined,
        
        bankCode: data.bankCode
        ||
        null
            ,
            
        fileFormat: data.fileFormat
        ||
        null
            ,
            
        totalAmount: data.totalAmount
        ||
        null
            ,
            
        recordCount: data.recordCount
        ||
        null
            ,
            
        generatedAt: data.generatedAt
        ||
        null
            ,
            
        submittedAt: data.submittedAt
        ||
        null
            ,
            
        fileHash: data.fileHash
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await bank_files.setPayrollRun( data.payrollRun || null, {
            transaction,
        });
        
        await bank_files.setGeneratedByUser( data.generatedByUser || null, {
            transaction,
        });
        

        

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

        return bank_files;
    }
    

    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_filesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                bankCode: item.bankCode
            ||
            null
            ,
            
                fileFormat: item.fileFormat
            ||
            null
            ,
            
                totalAmount: item.totalAmount
            ||
            null
            ,
            
                recordCount: item.recordCount
            ||
            null
            ,
            
                generatedAt: item.generatedAt
            ||
            null
            ,
            
                submittedAt: item.submittedAt
            ||
            null
            ,
            
                fileHash: item.fileHash
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return bank_files;
    }

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

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


        

        const updatePayload = {};
        
        if (data.bankCode !== undefined) updatePayload.bankCode = data.bankCode;
        
        
        if (data.fileFormat !== undefined) updatePayload.fileFormat = data.fileFormat;
        
        
        if (data.totalAmount !== undefined) updatePayload.totalAmount = data.totalAmount;
        
        
        if (data.recordCount !== undefined) updatePayload.recordCount = data.recordCount;
        
        
        if (data.generatedAt !== undefined) updatePayload.generatedAt = data.generatedAt;
        
        
        if (data.submittedAt !== undefined) updatePayload.submittedAt = data.submittedAt;
        
        
        if (data.fileHash !== undefined) updatePayload.fileHash = data.fileHash;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.payrollRun !== undefined) {
            await bank_files.setPayrollRun(
              
              data.payrollRun,
              
              { transaction }
            );
        }
        
        if (data.generatedByUser !== undefined) {
            await bank_files.setGeneratedByUser(
              
              data.generatedByUser,
              
              { transaction }
            );
        }
        

        
        

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

        return bank_files;
    }

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

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

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


        return bank_files;
    }

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

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

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

        await bank_files.destroy({
            transaction
        });

        return bank_files;
    }

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

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

        if (!bank_files) {
            return bank_files;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.payrollRun = await bank_files.getPayrollRun({
            transaction
        });
        
        
        output.filePath = await bank_files.getFilePath({
            transaction
        });
        
        
        output.generatedByUser = await bank_files.getGeneratedByUser({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

        const orderBy = null;

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

    let include = [

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

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



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

    ];

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

            
            if (filter.fileHash) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'bank_files',
                        'fileHash',
                        filter.fileHash,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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


      

      



            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,
                        },
                    };
                }
            }
        }
        

        

        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_files.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, ) {
        let where = {};
        
        

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

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

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

    
};

