
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');
const TenantAccess = require('./tenantAccess');



const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class Evidence_modelsDBApi {
    

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

        const evidence_models = await db.evidence_models.create(
            {
                id: data.id || undefined,
        
        evidence_claim: data.evidence_claim
        ||
        null
            ,
            
        artifact_type: data.artifact_type
        ||
        null
            ,
            
        required_fields: data.required_fields
        ||
        null
            ,
            
        approval_required_flag: data.approval_required_flag
        ||
        false
        
            ,
            
        retention_period: data.retention_period
        ||
        null
            ,
            
        evidence_strength: data.evidence_strength
        ||
        null
            ,
            
        collection_method: data.collection_method
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await evidence_models.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await evidence_models.setWorkflow( data.workflow || null, {
            transaction,
        });
        
        await evidence_models.setControl_requirement( data.control_requirement || null, {
            transaction,
        });
        
        await evidence_models.setSource_system( data.source_system || null, {
            transaction,
        });
        

        

        

        return evidence_models;
    }
    

    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 evidence_modelsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                evidence_claim: item.evidence_claim
            ||
            null
            ,
            
                artifact_type: item.artifact_type
            ||
            null
            ,
            
                required_fields: item.required_fields
            ||
            null
            ,
            
                approval_required_flag: item.approval_required_flag
            ||
            false
        
            ,
            
                retention_period: item.retention_period
            ||
            null
            ,
            
                evidence_strength: item.evidence_strength
            ||
            null
            ,
            
                collection_method: item.collection_method
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return evidence_models;
    }

    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 evidence_models = await TenantAccess.findByPkOrThrow(db.evidence_models, id, options);


        

        const updatePayload = {};
        
        if (data.evidence_claim !== undefined) updatePayload.evidence_claim = data.evidence_claim;
        
        
        if (data.artifact_type !== undefined) updatePayload.artifact_type = data.artifact_type;
        
        
        if (data.required_fields !== undefined) updatePayload.required_fields = data.required_fields;
        
        
        if (data.approval_required_flag !== undefined) updatePayload.approval_required_flag = data.approval_required_flag;
        
        
        if (data.retention_period !== undefined) updatePayload.retention_period = data.retention_period;
        
        
        if (data.evidence_strength !== undefined) updatePayload.evidence_strength = data.evidence_strength;
        
        
        if (data.collection_method !== undefined) updatePayload.collection_method = data.collection_method;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await evidence_models.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.workflow !== undefined) {
            await evidence_models.setWorkflow(
              
              data.workflow,
              
              { transaction }
            );
        }
        
        if (data.control_requirement !== undefined) {
            await evidence_models.setControl_requirement(
              
              data.control_requirement,
              
              { transaction }
            );
        }
        
        if (data.source_system !== undefined) {
            await evidence_models.setSource_system(
              
              data.source_system,
              
              { transaction }
            );
        }
        

        
        

        

        return evidence_models;
    }

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

        const evidence_models = await TenantAccess.findAllByIds(db.evidence_models, ids, options);

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


        return evidence_models;
    }

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

        const evidence_models = await TenantAccess.findByPkOrThrow(db.evidence_models, id, options);

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

        await evidence_models.destroy({
            transaction
        });

        return evidence_models;
    }

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

        const evidence_models = await TenantAccess.findOne(db.evidence_models, where, options);

        if (!evidence_models) {
            return evidence_models;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        output.artifacts_evidence_model = await evidence_models.getArtifacts_evidence_model({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await evidence_models.getOrganization({
            transaction
        });
        
        
        output.workflow = await evidence_models.getWorkflow({
            transaction
        });
        
        
        output.control_requirement = await evidence_models.getControl_requirement({
            transaction
        });
        
        
        output.source_system = await evidence_models.getSource_system({
            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.identity_workflows,
        as: 'workflow',
        
        where: filter.workflow ? {
          [Op.or]: [
            { id: { [Op.in]: filter.workflow.split('|').map(term => Utils.uuid(term)) } },
            {
              workflow_name: {
                [Op.or]: filter.workflow.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            
            if (filter.evidence_claim) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'evidence_models',
                        'evidence_claim',
                        filter.evidence_claim,
                    ),
                };
            }
            
            if (filter.required_fields) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'evidence_models',
                        'required_fields',
                        filter.required_fields,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'evidence_models',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

            

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

            
            if (filter.artifact_type) {
                where = {
                    ...where,
                artifact_type: filter.artifact_type,
            };
            }
            
            if (filter.approval_required_flag) {
                where = {
                    ...where,
                approval_required_flag: filter.approval_required_flag,
            };
            }
            
            if (filter.retention_period) {
                where = {
                    ...where,
                retention_period: filter.retention_period,
            };
            }
            
            if (filter.evidence_strength) {
                where = {
                    ...where,
                evidence_strength: filter.evidence_strength,
            };
            }
            
            if (filter.collection_method) {
                where = {
                    ...where,
                collection_method: filter.collection_method,
            };
            }
            


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

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

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

    
};

