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

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

        const id_verification_artifacts = await db.id_verification_artifacts.create(
            {
                id: data.id || undefined,
        
        id_document_type: data.id_document_type
        ||
        null
            ,
            
        quality_status: data.quality_status
        ||
        null
            ,
            
        quality_notes: data.quality_notes
        ||
        null
            ,
            
        match_score: data.match_score
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

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

        return id_verification_artifacts;
    }
    

    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 id_verification_artifactsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                id_document_type: item.id_document_type
            ||
            null
            ,
            
                quality_status: item.quality_status
            ||
            null
            ,
            
                quality_notes: item.quality_notes
            ||
            null
            ,
            
                match_score: item.match_score
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return id_verification_artifacts;
    }

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


        

        const updatePayload = {};
        
        if (data.id_document_type !== undefined) updatePayload.id_document_type = data.id_document_type;
        
        
        if (data.quality_status !== undefined) updatePayload.quality_status = data.quality_status;
        
        
        if (data.quality_notes !== undefined) updatePayload.quality_notes = data.quality_notes;
        
        
        if (data.match_score !== undefined) updatePayload.match_score = data.match_score;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

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

        return id_verification_artifacts;
    }

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

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

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


        return id_verification_artifacts;
    }

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

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

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

        await id_verification_artifacts.destroy({
            transaction
        });

        return id_verification_artifacts;
    }

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

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

        if (!id_verification_artifacts) {
            return id_verification_artifacts;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.authentication_attempt = await id_verification_artifacts.getAuthentication_attempt({
            transaction
        });
        
        
        output.document_images = await id_verification_artifacts.getDocument_images({
            transaction
        });
        
        
        output.face_images = await id_verification_artifacts.getFace_images({
            transaction
        });
        
        
        output.organizations = await id_verification_artifacts.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',
        
      },



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

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

    ];

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

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

            
            

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

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

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

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

            
            if (filter.id_document_type) {
                where = {
                    ...where,
                id_document_type: filter.id_document_type,
            };
            }
            
            if (filter.quality_status) {
                where = {
                    ...where,
                quality_status: filter.quality_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.id_verification_artifacts.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(
                        'id_verification_artifacts',
                        'id_document_type',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

