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

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

        const face_matches = await db.face_matches.create(
            {
                id: data.id || undefined,
        
        match_score: data.match_score
        ||
        null
            ,
            
        confidence_badge: data.confidence_badge
        ||
        null
            ,
            
        matched_at: data.matched_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await face_matches.setSelfie_reference( data.selfie_reference || null, {
            transaction,
        });
        
        await face_matches.setFace_detection( data.face_detection || null, {
            transaction,
        });
        
        await face_matches.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return face_matches;
    }
    

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

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

        // For each item created, replace relation files
        

        return face_matches;
    }

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


        

        const updatePayload = {};
        
        if (data.match_score !== undefined) updatePayload.match_score = data.match_score;
        
        
        if (data.confidence_badge !== undefined) updatePayload.confidence_badge = data.confidence_badge;
        
        
        if (data.matched_at !== undefined) updatePayload.matched_at = data.matched_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.selfie_reference !== undefined) {
            await face_matches.setSelfie_reference(
              
              data.selfie_reference,
              
              { transaction }
            );
        }
        
        if (data.face_detection !== undefined) {
            await face_matches.setFace_detection(
              
              data.face_detection,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await face_matches.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return face_matches;
    }

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

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

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


        return face_matches;
    }

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

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

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

        await face_matches.destroy({
            transaction
        });

        return face_matches;
    }

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

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

        if (!face_matches) {
            return face_matches;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.selfie_reference = await face_matches.getSelfie_reference({
            transaction
        });
        
        
        output.face_detection = await face_matches.getFace_detection({
            transaction
        });
        
        
        output.organizations = await face_matches.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.selfie_references,
        as: 'selfie_reference',
        
        where: filter.selfie_reference ? {
          [Op.or]: [
            { id: { [Op.in]: filter.selfie_reference.split('|').map(term => Utils.uuid(term)) } },
            {
              status: {
                [Op.or]: filter.selfie_reference.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.face_detections,
        as: 'face_detection',
        
        where: filter.face_detection ? {
          [Op.or]: [
            { id: { [Op.in]: filter.face_detection.split('|').map(term => Utils.uuid(term)) } },
            {
              confidence: {
                [Op.or]: filter.face_detection.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.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.matched_atRange) {
                const [start, end] = filter.matched_atRange;

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

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

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

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


      

      

      
      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.face_matches.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(
                        'face_matches',
                        'confidence_badge',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

