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

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

        const kyc_verifications = await db.kyc_verifications.create(
            {
                id: data.id || undefined,
        
        status: data.status
        ||
        null
            ,
            
        document_type: data.document_type
        ||
        null
            ,
            
        full_name_on_document: data.full_name_on_document
        ||
        null
            ,
            
        document_number: data.document_number
        ||
        null
            ,
            
        submitted_at: data.submitted_at
        ||
        null
            ,
            
        reviewed_at: data.reviewed_at
        ||
        null
            ,
            
        review_note: data.review_note
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await kyc_verifications.setUser( data.user || null, {
            transaction,
        });
        

        

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

        return kyc_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 kyc_verificationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                status: item.status
            ||
            null
            ,
            
                document_type: item.document_type
            ||
            null
            ,
            
                full_name_on_document: item.full_name_on_document
            ||
            null
            ,
            
                document_number: item.document_number
            ||
            null
            ,
            
                submitted_at: item.submitted_at
            ||
            null
            ,
            
                reviewed_at: item.reviewed_at
            ||
            null
            ,
            
                review_note: item.review_note
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return kyc_verifications;
    }

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

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


        

        const updatePayload = {};
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.document_type !== undefined) updatePayload.document_type = data.document_type;
        
        
        if (data.full_name_on_document !== undefined) updatePayload.full_name_on_document = data.full_name_on_document;
        
        
        if (data.document_number !== undefined) updatePayload.document_number = data.document_number;
        
        
        if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
        
        
        if (data.reviewed_at !== undefined) updatePayload.reviewed_at = data.reviewed_at;
        
        
        if (data.review_note !== undefined) updatePayload.review_note = data.review_note;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await kyc_verifications.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        

        
        

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

        return kyc_verifications;
    }

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

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

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


        return kyc_verifications;
    }

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

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

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

        await kyc_verifications.destroy({
            transaction
        });

        return kyc_verifications;
    }

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

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

        if (!kyc_verifications) {
            return kyc_verifications;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await kyc_verifications.getUser({
            transaction
        });
        
        
        output.document_files = await kyc_verifications.getDocument_files({
            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.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



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

    ];

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

            
            if (filter.document_type) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'kyc_verifications',
                        'document_type',
                        filter.document_type,
                    ),
                };
            }
            
            if (filter.full_name_on_document) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'kyc_verifications',
                        'full_name_on_document',
                        filter.full_name_on_document,
                    ),
                };
            }
            
            if (filter.document_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'kyc_verifications',
                        'document_number',
                        filter.document_number,
                    ),
                };
            }
            
            if (filter.review_note) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'kyc_verifications',
                        'review_note',
                        filter.review_note,
                    ),
                };
            }
            

            
            

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    reviewed_at: {
                    ...where.reviewed_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.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.kyc_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, ) {
        let where = {};
        
        

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

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

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

    
};

