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

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

        const risk_items = await db.risk_items.create(
            {
                id: data.id || undefined,
        
        hazard_id: data.hazard_id
        ||
        null
            ,
            
        hazard_description: data.hazard_description
        ||
        null
            ,
            
        sequence_of_events: data.sequence_of_events
        ||
        null
            ,
            
        severity: data.severity
        ||
        null
            ,
            
        occurrence: data.occurrence
        ||
        null
            ,
            
        detectability: data.detectability
        ||
        null
            ,
            
        risk_level_initial: data.risk_level_initial
        ||
        null
            ,
            
        risk_controls: data.risk_controls
        ||
        null
            ,
            
        risk_level_residual: data.risk_level_residual
        ||
        null
            ,
            
        verification_of_controls: data.verification_of_controls
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await risk_items.setRisk_assessment( data.risk_assessment || null, {
            transaction,
        });
        

        

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

        return risk_items;
    }
    

    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_itemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                hazard_id: item.hazard_id
            ||
            null
            ,
            
                hazard_description: item.hazard_description
            ||
            null
            ,
            
                sequence_of_events: item.sequence_of_events
            ||
            null
            ,
            
                severity: item.severity
            ||
            null
            ,
            
                occurrence: item.occurrence
            ||
            null
            ,
            
                detectability: item.detectability
            ||
            null
            ,
            
                risk_level_initial: item.risk_level_initial
            ||
            null
            ,
            
                risk_controls: item.risk_controls
            ||
            null
            ,
            
                risk_level_residual: item.risk_level_residual
            ||
            null
            ,
            
                verification_of_controls: item.verification_of_controls
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return risk_items;
    }

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

        const risk_items = await db.risk_items.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.hazard_id !== undefined) updatePayload.hazard_id = data.hazard_id;
        
        
        if (data.hazard_description !== undefined) updatePayload.hazard_description = data.hazard_description;
        
        
        if (data.sequence_of_events !== undefined) updatePayload.sequence_of_events = data.sequence_of_events;
        
        
        if (data.severity !== undefined) updatePayload.severity = data.severity;
        
        
        if (data.occurrence !== undefined) updatePayload.occurrence = data.occurrence;
        
        
        if (data.detectability !== undefined) updatePayload.detectability = data.detectability;
        
        
        if (data.risk_level_initial !== undefined) updatePayload.risk_level_initial = data.risk_level_initial;
        
        
        if (data.risk_controls !== undefined) updatePayload.risk_controls = data.risk_controls;
        
        
        if (data.risk_level_residual !== undefined) updatePayload.risk_level_residual = data.risk_level_residual;
        
        
        if (data.verification_of_controls !== undefined) updatePayload.verification_of_controls = data.verification_of_controls;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.risk_assessment !== undefined) {
            await risk_items.setRisk_assessment(
              
              data.risk_assessment,
              
              { transaction }
            );
        }
        

        
        

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

        return risk_items;
    }

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

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

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


        return risk_items;
    }

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

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

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

        await risk_items.destroy({
            transaction
        });

        return risk_items;
    }

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

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

        if (!risk_items) {
            return risk_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.risk_assessment = await risk_items.getRisk_assessment({
            transaction
        });
        
        
        output.evidence_files = await risk_items.getEvidence_files({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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



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

    ];

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

            
            if (filter.hazard_id) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'risk_items',
                        'hazard_id',
                        filter.hazard_id,
                    ),
                };
            }
            
            if (filter.hazard_description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'risk_items',
                        'hazard_description',
                        filter.hazard_description,
                    ),
                };
            }
            
            if (filter.sequence_of_events) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'risk_items',
                        'sequence_of_events',
                        filter.sequence_of_events,
                    ),
                };
            }
            
            if (filter.risk_controls) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'risk_items',
                        'risk_controls',
                        filter.risk_controls,
                    ),
                };
            }
            
            if (filter.verification_of_controls) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'risk_items',
                        'verification_of_controls',
                        filter.verification_of_controls,
                    ),
                };
            }
            

            
            

            

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

            
            if (filter.severity) {
                where = {
                    ...where,
                severity: filter.severity,
            };
            }
            
            if (filter.occurrence) {
                where = {
                    ...where,
                occurrence: filter.occurrence,
            };
            }
            
            if (filter.detectability) {
                where = {
                    ...where,
                detectability: filter.detectability,
            };
            }
            
            if (filter.risk_level_initial) {
                where = {
                    ...where,
                risk_level_initial: filter.risk_level_initial,
            };
            }
            
            if (filter.risk_level_residual) {
                where = {
                    ...where,
                risk_level_residual: filter.risk_level_residual,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


      



            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,
                        },
                    };
                }
            }
        }
        

        

        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_items.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, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'risk_items',
                        'hazard_id',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

