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

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

        const risk_assessments = await db.risk_assessments.create(
            {
                id: data.id || undefined,
        
        assessed_at: data.assessed_at
        ||
        null
            ,
            
        scope: data.scope
        ||
        null
            ,
            
        overall_risk_score: data.overall_risk_score
        ||
        null
            ,
            
        risk_level: data.risk_level
        ||
        null
            ,
            
        top_risks: data.top_risks
        ||
        null
            ,
            
        recommendations: data.recommendations
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await risk_assessments.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await risk_assessments.setAsset( data.asset || null, {
            transaction,
        });
        

        

        

        return risk_assessments;
    }
    

    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 risk_assessmentsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                assessed_at: item.assessed_at
            ||
            null
            ,
            
                scope: item.scope
            ||
            null
            ,
            
                overall_risk_score: item.overall_risk_score
            ||
            null
            ,
            
                risk_level: item.risk_level
            ||
            null
            ,
            
                top_risks: item.top_risks
            ||
            null
            ,
            
                recommendations: item.recommendations
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return risk_assessments;
    }

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


        

        const updatePayload = {};
        
        if (data.assessed_at !== undefined) updatePayload.assessed_at = data.assessed_at;
        
        
        if (data.scope !== undefined) updatePayload.scope = data.scope;
        
        
        if (data.overall_risk_score !== undefined) updatePayload.overall_risk_score = data.overall_risk_score;
        
        
        if (data.risk_level !== undefined) updatePayload.risk_level = data.risk_level;
        
        
        if (data.top_risks !== undefined) updatePayload.top_risks = data.top_risks;
        
        
        if (data.recommendations !== undefined) updatePayload.recommendations = data.recommendations;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await risk_assessments.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.asset !== undefined) {
            await risk_assessments.setAsset(
              
              data.asset,
              
              { transaction }
            );
        }
        

        
        

        

        return risk_assessments;
    }

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

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

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


        return risk_assessments;
    }

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

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

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

        await risk_assessments.destroy({
            transaction
        });

        return risk_assessments;
    }

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

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

        if (!risk_assessments) {
            return risk_assessments;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await risk_assessments.getOrganization({
            transaction
        });
        
        
        output.asset = await risk_assessments.getAsset({
            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: 'organization',
        
      },

      {
        model: db.assets,
        as: 'asset',
        
        where: filter.asset ? {
          [Op.or]: [
            { id: { [Op.in]: filter.asset.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.asset.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.top_risks) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'risk_assessments',
                        'top_risks',
                        filter.top_risks,
                    ),
                };
            }
            
            if (filter.recommendations) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'risk_assessments',
                        'recommendations',
                        filter.recommendations,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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


      
      if (filter.organization) {
        const listItems = filter.organization.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationId: {[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.risk_assessments.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(
                        'risk_assessments',
                        'risk_level',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

