
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,
        
        risk_file_name: data.risk_file_name
        ||
        null
            ,
            
        risk_file_code: data.risk_file_code
        ||
        null
            ,
            
        methodology: data.methodology
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        created_on: data.created_on
        ||
        null
            ,
            
        review_due_at: data.review_due_at
        ||
        null
            ,
            
        scope: data.scope
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await risk_assessments.setProduct( data.product || null, {
            transaction,
        });
        
        await risk_assessments.setOwner( data.owner || null, {
            transaction,
        });
        

        

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

        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,
                
                risk_file_name: item.risk_file_name
            ||
            null
            ,
            
                risk_file_code: item.risk_file_code
            ||
            null
            ,
            
                methodology: item.methodology
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                created_on: item.created_on
            ||
            null
            ,
            
                review_due_at: item.review_due_at
            ||
            null
            ,
            
                scope: item.scope
            ||
            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
        
        for (let i = 0; i < risk_assessments.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.risk_assessments.getTableName(),
                    belongsToColumn: 'risk_files',
                    belongsToId: risk_assessments[i].id,
                },
                data[i].risk_files,
                options,
            );
        }
        

        return risk_assessments;
    }

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

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


        

        const updatePayload = {};
        
        if (data.risk_file_name !== undefined) updatePayload.risk_file_name = data.risk_file_name;
        
        
        if (data.risk_file_code !== undefined) updatePayload.risk_file_code = data.risk_file_code;
        
        
        if (data.methodology !== undefined) updatePayload.methodology = data.methodology;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.created_on !== undefined) updatePayload.created_on = data.created_on;
        
        
        if (data.review_due_at !== undefined) updatePayload.review_due_at = data.review_due_at;
        
        
        if (data.scope !== undefined) updatePayload.scope = data.scope;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.product !== undefined) {
            await risk_assessments.setProduct(
              
              data.product,
              
              { transaction }
            );
        }
        
        if (data.owner !== undefined) {
            await risk_assessments.setOwner(
              
              data.owner,
              
              { transaction }
            );
        }
        

        
        

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

        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.risk_items_risk_assessment = await risk_assessments.getRisk_items_risk_assessment({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        output.product = await risk_assessments.getProduct({
            transaction
        });
        
        
        output.owner = await risk_assessments.getOwner({
            transaction
        });
        
        
        output.risk_files = await risk_assessments.getRisk_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.products,
        as: 'product',
        
        where: filter.product ? {
          [Op.or]: [
            { id: { [Op.in]: filter.product.split('|').map(term => Utils.uuid(term)) } },
            {
              product_name: {
                [Op.or]: filter.product.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



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

    ];

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

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

            
            

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

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

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

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

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

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

            
            if (filter.methodology) {
                where = {
                    ...where,
                methodology: filter.methodology,
            };
            }
            
            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_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, ) {
        let where = {};
        
        

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

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

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

    
};

