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

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

        const trust_profiles = await db.trust_profiles.create(
            {
                id: data.id || undefined,
        
        trust_score: data.trust_score
        ||
        null
            ,
            
        trust_tier: data.trust_tier
        ||
        null
            ,
            
        score_last_calculated_at: data.score_last_calculated_at
        ||
        null
            ,
            
        is_human_verified: data.is_human_verified
        ||
        false
        
            ,
            
        is_business_verified: data.is_business_verified
        ||
        false
        
            ,
            
        is_identity_verified: data.is_identity_verified
        ||
        false
        
            ,
            
        is_tax_verified: data.is_tax_verified
        ||
        false
        
            ,
            
        risk_flags_summary: data.risk_flags_summary
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await trust_profiles.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return trust_profiles;
    }
    

    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 trust_profilesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                trust_score: item.trust_score
            ||
            null
            ,
            
                trust_tier: item.trust_tier
            ||
            null
            ,
            
                score_last_calculated_at: item.score_last_calculated_at
            ||
            null
            ,
            
                is_human_verified: item.is_human_verified
            ||
            false
        
            ,
            
                is_business_verified: item.is_business_verified
            ||
            false
        
            ,
            
                is_identity_verified: item.is_identity_verified
            ||
            false
        
            ,
            
                is_tax_verified: item.is_tax_verified
            ||
            false
        
            ,
            
                risk_flags_summary: item.risk_flags_summary
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return trust_profiles;
    }

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


        

        const updatePayload = {};
        
        if (data.trust_score !== undefined) updatePayload.trust_score = data.trust_score;
        
        
        if (data.trust_tier !== undefined) updatePayload.trust_tier = data.trust_tier;
        
        
        if (data.score_last_calculated_at !== undefined) updatePayload.score_last_calculated_at = data.score_last_calculated_at;
        
        
        if (data.is_human_verified !== undefined) updatePayload.is_human_verified = data.is_human_verified;
        
        
        if (data.is_business_verified !== undefined) updatePayload.is_business_verified = data.is_business_verified;
        
        
        if (data.is_identity_verified !== undefined) updatePayload.is_identity_verified = data.is_identity_verified;
        
        
        if (data.is_tax_verified !== undefined) updatePayload.is_tax_verified = data.is_tax_verified;
        
        
        if (data.risk_flags_summary !== undefined) updatePayload.risk_flags_summary = data.risk_flags_summary;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return trust_profiles;
    }

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

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

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


        return trust_profiles;
    }

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

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

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

        await trust_profiles.destroy({
            transaction
        });

        return trust_profiles;
    }

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

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

        if (!trust_profiles) {
            return trust_profiles;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organizations = await trust_profiles.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.organizations,
        as: 'organizations',
        
      },



    ];

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

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

            
            

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

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

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

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

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

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

            
            if (filter.trust_tier) {
                where = {
                    ...where,
                trust_tier: filter.trust_tier,
            };
            }
            
            if (filter.is_human_verified) {
                where = {
                    ...where,
                is_human_verified: filter.is_human_verified,
            };
            }
            
            if (filter.is_business_verified) {
                where = {
                    ...where,
                is_business_verified: filter.is_business_verified,
            };
            }
            
            if (filter.is_identity_verified) {
                where = {
                    ...where,
                is_identity_verified: filter.is_identity_verified,
            };
            }
            
            if (filter.is_tax_verified) {
                where = {
                    ...where,
                is_tax_verified: filter.is_tax_verified,
            };
            }
            


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

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

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

    
};

