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

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

        const risk_analyses = await db.risk_analyses.create(
            {
                id: data.id || undefined,
        
        overall_score: data.overall_score
        ||
        null
            ,
            
        factors_json: data.factors_json
        ||
        null
            ,
            
        optimization_suggestions_json: data.optimization_suggestions_json
        ||
        null
            ,
            
        analyzed_at: data.analyzed_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await risk_analyses.setDeclaration( data.declaration || null, {
            transaction,
        });
        
        await risk_analyses.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return risk_analyses;
    }
    

    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_analysesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                overall_score: item.overall_score
            ||
            null
            ,
            
                factors_json: item.factors_json
            ||
            null
            ,
            
                optimization_suggestions_json: item.optimization_suggestions_json
            ||
            null
            ,
            
                analyzed_at: item.analyzed_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return risk_analyses;
    }

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


        

        const updatePayload = {};
        
        if (data.overall_score !== undefined) updatePayload.overall_score = data.overall_score;
        
        
        if (data.factors_json !== undefined) updatePayload.factors_json = data.factors_json;
        
        
        if (data.optimization_suggestions_json !== undefined) updatePayload.optimization_suggestions_json = data.optimization_suggestions_json;
        
        
        if (data.analyzed_at !== undefined) updatePayload.analyzed_at = data.analyzed_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return risk_analyses;
    }

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

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

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


        return risk_analyses;
    }

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

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

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

        await risk_analyses.destroy({
            transaction
        });

        return risk_analyses;
    }

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

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

        if (!risk_analyses) {
            return risk_analyses;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.declaration = await risk_analyses.getDeclaration({
            transaction
        });
        
        
        output.organizations = await risk_analyses.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.declarations,
        as: 'declaration',
        
        where: filter.declaration ? {
          [Op.or]: [
            { id: { [Op.in]: filter.declaration.split('|').map(term => Utils.uuid(term)) } },
            {
              status: {
                [Op.or]: filter.declaration.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.factors_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'risk_analyses',
                        'factors_json',
                        filter.factors_json,
                    ),
                };
            }
            
            if (filter.optimization_suggestions_json) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'risk_analyses',
                        'optimization_suggestions_json',
                        filter.optimization_suggestions_json,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            


      

      
      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.risk_analyses.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_analyses',
                        'overall_score',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

