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

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

        const artifacts = await db.artifacts.create(
            {
                id: data.id || undefined,
        
        artifact_name: data.artifact_name
        ||
        null
            ,
            
        artifact_type: data.artifact_type
        ||
        null
            ,
            
        artifact_reference: data.artifact_reference
        ||
        null
            ,
            
        collected_at: data.collected_at
        ||
        null
            ,
            
        event_timestamp: data.event_timestamp
        ||
        null
            ,
            
        subject_user: data.subject_user
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        validation_notes: data.validation_notes
        ||
        null
            ,
            
        evidence_strength_score: data.evidence_strength_score
        ||
        null
            ,
            
        chain_integrity_score: data.chain_integrity_score
        ||
        null
            ,
            
        retention_expiry: data.retention_expiry
        ||
        null
            ,
            
        tags: data.tags
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await artifacts.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await artifacts.setWorkflow( data.workflow || null, {
            transaction,
        });
        
        await artifacts.setEvidence_model( data.evidence_model || null, {
            transaction,
        });
        
        await artifacts.setSource_system( data.source_system || null, {
            transaction,
        });
        
        await artifacts.setCollected_by_user( data.collected_by_user || null, {
            transaction,
        });
        
        await artifacts.setApprover_user( data.approver_user || null, {
            transaction,
        });
        

        

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

        return artifacts;
    }
    

    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 artifactsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                artifact_name: item.artifact_name
            ||
            null
            ,
            
                artifact_type: item.artifact_type
            ||
            null
            ,
            
                artifact_reference: item.artifact_reference
            ||
            null
            ,
            
                collected_at: item.collected_at
            ||
            null
            ,
            
                event_timestamp: item.event_timestamp
            ||
            null
            ,
            
                subject_user: item.subject_user
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                validation_notes: item.validation_notes
            ||
            null
            ,
            
                evidence_strength_score: item.evidence_strength_score
            ||
            null
            ,
            
                chain_integrity_score: item.chain_integrity_score
            ||
            null
            ,
            
                retention_expiry: item.retention_expiry
            ||
            null
            ,
            
                tags: item.tags
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return artifacts;
    }

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


        

        const updatePayload = {};
        
        if (data.artifact_name !== undefined) updatePayload.artifact_name = data.artifact_name;
        
        
        if (data.artifact_type !== undefined) updatePayload.artifact_type = data.artifact_type;
        
        
        if (data.artifact_reference !== undefined) updatePayload.artifact_reference = data.artifact_reference;
        
        
        if (data.collected_at !== undefined) updatePayload.collected_at = data.collected_at;
        
        
        if (data.event_timestamp !== undefined) updatePayload.event_timestamp = data.event_timestamp;
        
        
        if (data.subject_user !== undefined) updatePayload.subject_user = data.subject_user;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.validation_notes !== undefined) updatePayload.validation_notes = data.validation_notes;
        
        
        if (data.evidence_strength_score !== undefined) updatePayload.evidence_strength_score = data.evidence_strength_score;
        
        
        if (data.chain_integrity_score !== undefined) updatePayload.chain_integrity_score = data.chain_integrity_score;
        
        
        if (data.retention_expiry !== undefined) updatePayload.retention_expiry = data.retention_expiry;
        
        
        if (data.tags !== undefined) updatePayload.tags = data.tags;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await artifacts.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.workflow !== undefined) {
            await artifacts.setWorkflow(
              
              data.workflow,
              
              { transaction }
            );
        }
        
        if (data.evidence_model !== undefined) {
            await artifacts.setEvidence_model(
              
              data.evidence_model,
              
              { transaction }
            );
        }
        
        if (data.source_system !== undefined) {
            await artifacts.setSource_system(
              
              data.source_system,
              
              { transaction }
            );
        }
        
        if (data.collected_by_user !== undefined) {
            await artifacts.setCollected_by_user(
              
              data.collected_by_user,
              
              { transaction }
            );
        }
        
        if (data.approver_user !== undefined) {
            await artifacts.setApprover_user(
              
              data.approver_user,
              
              { transaction }
            );
        }
        

        
        

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

        return artifacts;
    }

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

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

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


        return artifacts;
    }

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

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

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

        await artifacts.destroy({
            transaction
        });

        return artifacts;
    }

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

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

        if (!artifacts) {
            return artifacts;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.remediation_items_linked_artifact = await artifacts.getRemediation_items_linked_artifact({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await artifacts.getOrganization({
            transaction
        });
        
        
        output.workflow = await artifacts.getWorkflow({
            transaction
        });
        
        
        output.evidence_model = await artifacts.getEvidence_model({
            transaction
        });
        
        
        output.source_system = await artifacts.getSource_system({
            transaction
        });
        
        
        output.collected_by_user = await artifacts.getCollected_by_user({
            transaction
        });
        
        
        output.approver_user = await artifacts.getApprover_user({
            transaction
        });
        
        
        output.uploaded_files = await artifacts.getUploaded_files({
            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.evidence_models,
        as: 'evidence_model',
        
        where: filter.evidence_model ? {
          [Op.or]: [
            { id: { [Op.in]: filter.evidence_model.split('|').map(term => Utils.uuid(term)) } },
            {
              evidence_claim: {
                [Op.or]: filter.evidence_model.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}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



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

    ];

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

            
            if (filter.artifact_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'artifacts',
                        'artifact_name',
                        filter.artifact_name,
                    ),
                };
            }
            
            if (filter.artifact_reference) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'artifacts',
                        'artifact_reference',
                        filter.artifact_reference,
                    ),
                };
            }
            
            if (filter.subject_user) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'artifacts',
                        'subject_user',
                        filter.subject_user,
                    ),
                };
            }
            
            if (filter.validation_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'artifacts',
                        'validation_notes',
                        filter.validation_notes,
                    ),
                };
            }
            
            if (filter.tags) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'artifacts',
                        'tags',
                        filter.tags,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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

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

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

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

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

            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.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


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

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

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

    
};

