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

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

        const detections = await db.detections.create(
            {
                id: data.id || undefined,
        
        detected_at: data.detected_at
        ||
        null
            ,
            
        detection_type: data.detection_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        confidence: data.confidence
        ||
        null
            ,
            
        risk_score: data.risk_score
        ||
        null
            ,
            
        title: data.title
        ||
        null
            ,
            
        evidence: data.evidence
        ||
        null
            ,
            
        requires_response: data.requires_response
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await detections.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await detections.setEvent( data.event || null, {
            transaction,
        });
        
        await detections.setModel( data.model || null, {
            transaction,
        });
        

        

        

        return detections;
    }
    

    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 detectionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                detected_at: item.detected_at
            ||
            null
            ,
            
                detection_type: item.detection_type
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                confidence: item.confidence
            ||
            null
            ,
            
                risk_score: item.risk_score
            ||
            null
            ,
            
                title: item.title
            ||
            null
            ,
            
                evidence: item.evidence
            ||
            null
            ,
            
                requires_response: item.requires_response
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return detections;
    }

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


        

        const updatePayload = {};
        
        if (data.detected_at !== undefined) updatePayload.detected_at = data.detected_at;
        
        
        if (data.detection_type !== undefined) updatePayload.detection_type = data.detection_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.confidence !== undefined) updatePayload.confidence = data.confidence;
        
        
        if (data.risk_score !== undefined) updatePayload.risk_score = data.risk_score;
        
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.evidence !== undefined) updatePayload.evidence = data.evidence;
        
        
        if (data.requires_response !== undefined) updatePayload.requires_response = data.requires_response;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await detections.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.event !== undefined) {
            await detections.setEvent(
              
              data.event,
              
              { transaction }
            );
        }
        
        if (data.model !== undefined) {
            await detections.setModel(
              
              data.model,
              
              { transaction }
            );
        }
        

        
        

        

        return detections;
    }

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

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

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


        return detections;
    }

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

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

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

        await detections.destroy({
            transaction
        });

        return detections;
    }

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

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

        if (!detections) {
            return detections;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await detections.getOrganization({
            transaction
        });
        
        
        output.event = await detections.getEvent({
            transaction
        });
        
        
        output.model = await detections.getModel({
            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.telemetry_events,
        as: 'event',
        
        where: filter.event ? {
          [Op.or]: [
            { id: { [Op.in]: filter.event.split('|').map(term => Utils.uuid(term)) } },
            {
              summary: {
                [Op.or]: filter.event.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'detections',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.evidence) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'detections',
                        'evidence',
                        filter.evidence,
                    ),
                };
            }
            

            
            

            
            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.confidenceRange) {
                const [start, end] = filter.confidenceRange;

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

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

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

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

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

            
            if (filter.detection_type) {
                where = {
                    ...where,
                detection_type: filter.detection_type,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            
            if (filter.requires_response) {
                where = {
                    ...where,
                requires_response: filter.requires_response,
            };
            }
            


      
      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.detections.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(
                        'detections',
                        'title',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

