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

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

        const risk_alerts = await db.risk_alerts.create(
            {
                id: data.id || undefined,
        
        risk_type: data.risk_type
        ||
        null
            ,
            
        severity: data.severity
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        detected_at: data.detected_at
        ||
        null
            ,
            
        title_text: data.title_text
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        source_reference: data.source_reference
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await risk_alerts.setBranch( data.branch || null, {
            transaction,
        });
        
        await risk_alerts.setAssigned_to( data.assigned_to || null, {
            transaction,
        });
        
        await risk_alerts.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return risk_alerts;
    }
    

    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_alertsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                risk_type: item.risk_type
            ||
            null
            ,
            
                severity: item.severity
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                detected_at: item.detected_at
            ||
            null
            ,
            
                title_text: item.title_text
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                source_reference: item.source_reference
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return risk_alerts;
    }

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


        

        const updatePayload = {};
        
        if (data.risk_type !== undefined) updatePayload.risk_type = data.risk_type;
        
        
        if (data.severity !== undefined) updatePayload.severity = data.severity;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.detected_at !== undefined) updatePayload.detected_at = data.detected_at;
        
        
        if (data.title_text !== undefined) updatePayload.title_text = data.title_text;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.source_reference !== undefined) updatePayload.source_reference = data.source_reference;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.branch !== undefined) {
            await risk_alerts.setBranch(
              
              data.branch,
              
              { transaction }
            );
        }
        
        if (data.assigned_to !== undefined) {
            await risk_alerts.setAssigned_to(
              
              data.assigned_to,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await risk_alerts.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return risk_alerts;
    }

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

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

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


        return risk_alerts;
    }

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

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

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

        await risk_alerts.destroy({
            transaction
        });

        return risk_alerts;
    }

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

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

        if (!risk_alerts) {
            return risk_alerts;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.branch = await risk_alerts.getBranch({
            transaction
        });
        
        
        output.assigned_to = await risk_alerts.getAssigned_to({
            transaction
        });
        
        
        output.organizations = await risk_alerts.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.branches,
        as: 'branch',
        
        where: filter.branch ? {
          [Op.or]: [
            { id: { [Op.in]: filter.branch.split('|').map(term => Utils.uuid(term)) } },
            {
              branch_name: {
                [Op.or]: filter.branch.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.users,
        as: 'assigned_to',
        
        where: filter.assigned_to ? {
          [Op.or]: [
            { id: { [Op.in]: filter.assigned_to.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.assigned_to.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.title_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'risk_alerts',
                        'title_text',
                        filter.title_text,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'risk_alerts',
                        'description',
                        filter.description,
                    ),
                };
            }
            
            if (filter.source_reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'risk_alerts',
                        'source_reference',
                        filter.source_reference,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.risk_type) {
                where = {
                    ...where,
                risk_type: filter.risk_type,
            };
            }
            
            if (filter.severity) {
                where = {
                    ...where,
                severity: filter.severity,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


      

      

      
      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_alerts.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_alerts',
                        'title_text',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

