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

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

        const identity_verifications = await db.identity_verifications.create(
            {
                id: data.id || undefined,
        
        verification_type: data.verification_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        submitted_at: data.submitted_at
        ||
        null
            ,
            
        reviewed_at: data.reviewed_at
        ||
        null
            ,
            
        expires_at: data.expires_at
        ||
        null
            ,
            
        document_number: data.document_number
        ||
        null
            ,
            
        match_confidence: data.match_confidence
        ||
        null
            ,
            
        review_notes: data.review_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await identity_verifications.setUser( data.user || null, {
            transaction,
        });
        
        await identity_verifications.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

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

        return identity_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 identity_verificationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                verification_type: item.verification_type
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                submitted_at: item.submitted_at
            ||
            null
            ,
            
                reviewed_at: item.reviewed_at
            ||
            null
            ,
            
                expires_at: item.expires_at
            ||
            null
            ,
            
                document_number: item.document_number
            ||
            null
            ,
            
                match_confidence: item.match_confidence
            ||
            null
            ,
            
                review_notes: item.review_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

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


        

        const updatePayload = {};
        
        if (data.verification_type !== undefined) updatePayload.verification_type = data.verification_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.submitted_at !== undefined) updatePayload.submitted_at = data.submitted_at;
        
        
        if (data.reviewed_at !== undefined) updatePayload.reviewed_at = data.reviewed_at;
        
        
        if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
        
        
        if (data.document_number !== undefined) updatePayload.document_number = data.document_number;
        
        
        if (data.match_confidence !== undefined) updatePayload.match_confidence = data.match_confidence;
        
        
        if (data.review_notes !== undefined) updatePayload.review_notes = data.review_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

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

        return identity_verifications;
    }

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

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

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


        return identity_verifications;
    }

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

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

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

        await identity_verifications.destroy({
            transaction
        });

        return identity_verifications;
    }

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

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

        if (!identity_verifications) {
            return identity_verifications;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await identity_verifications.getUser({
            transaction
        });
        
        
        output.document_files = await identity_verifications.getDocument_files({
            transaction
        });
        
        
        output.selfie_images = await identity_verifications.getSelfie_images({
            transaction
        });
        
        
        output.organizations = await identity_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.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.organizations,
        as: 'organizations',
        
      },



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

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

    ];

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

            
            if (filter.document_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'identity_verifications',
                        'document_number',
                        filter.document_number,
                    ),
                };
            }
            
            if (filter.review_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'identity_verifications',
                        'review_notes',
                        filter.review_notes,
                    ),
                };
            }
            

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

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

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

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

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

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

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

            
            if (filter.verification_type) {
                where = {
                    ...where,
                verification_type: filter.verification_type,
            };
            }
            
            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.identity_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(
                        'identity_verifications',
                        'document_number',
                        query,
                    ),
                ],
            };
        }

        const records = await db.identity_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,
        }));
    }

    
};

