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

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

        const identity_workflows = await db.identity_workflows.create(
            {
                id: data.id || undefined,
        
        workflow_name: data.workflow_name
        ||
        null
            ,
            
        workflow_type: data.workflow_type
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        risk_level: data.risk_level
        ||
        null
            ,
            
        owner_role: data.owner_role
        ||
        null
            ,
            
        source_trigger_type: data.source_trigger_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        recurrence_type: data.recurrence_type
        ||
        null
            ,
            
        target_sla_hours: data.target_sla_hours
        ||
        null
            ,
            
        coverage_gap_notes: data.coverage_gap_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await identity_workflows.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        

        
        await identity_workflows.setLinked_systems(data.linked_systems || [], {
            transaction,
        });
        
        await identity_workflows.setLinked_controls(data.linked_controls || [], {
            transaction,
        });
        

        

        return identity_workflows;
    }
    

    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 identity_workflowsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                workflow_name: item.workflow_name
            ||
            null
            ,
            
                workflow_type: item.workflow_type
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                risk_level: item.risk_level
            ||
            null
            ,
            
                owner_role: item.owner_role
            ||
            null
            ,
            
                source_trigger_type: item.source_trigger_type
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                recurrence_type: item.recurrence_type
            ||
            null
            ,
            
                target_sla_hours: item.target_sla_hours
            ||
            null
            ,
            
                coverage_gap_notes: item.coverage_gap_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return identity_workflows;
    }

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


        

        const updatePayload = {};
        
        if (data.workflow_name !== undefined) updatePayload.workflow_name = data.workflow_name;
        
        
        if (data.workflow_type !== undefined) updatePayload.workflow_type = data.workflow_type;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.risk_level !== undefined) updatePayload.risk_level = data.risk_level;
        
        
        if (data.owner_role !== undefined) updatePayload.owner_role = data.owner_role;
        
        
        if (data.source_trigger_type !== undefined) updatePayload.source_trigger_type = data.source_trigger_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.recurrence_type !== undefined) updatePayload.recurrence_type = data.recurrence_type;
        
        
        if (data.target_sla_hours !== undefined) updatePayload.target_sla_hours = data.target_sla_hours;
        
        
        if (data.coverage_gap_notes !== undefined) updatePayload.coverage_gap_notes = data.coverage_gap_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await identity_workflows.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        

        
        
        if (data.linked_systems !== undefined) {
            await identity_workflows.setLinked_systems(data.linked_systems, { transaction });
        }
        
        if (data.linked_controls !== undefined) {
            await identity_workflows.setLinked_controls(data.linked_controls, { transaction });
        }
        

        

        return identity_workflows;
    }

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

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

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


        return identity_workflows;
    }

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

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

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

        await identity_workflows.destroy({
            transaction
        });

        return identity_workflows;
    }

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

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

        if (!identity_workflows) {
            return identity_workflows;
        }

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

        
        
        
        
        
        
        
        
        
        
        output.evidence_models_workflow = await identity_workflows.getEvidence_models_workflow({
            transaction
        });
        
        
        output.artifacts_workflow = await identity_workflows.getArtifacts_workflow({
            transaction
        });
        
        
        output.sampled_subjects_workflow = await identity_workflows.getSampled_subjects_workflow({
            transaction
        });
        
        
        output.proof_packets_workflow = await identity_workflows.getProof_packets_workflow({
            transaction
        });
        
        
        output.remediation_items_linked_workflow = await identity_workflows.getRemediation_items_linked_workflow({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await identity_workflows.getOrganization({
            transaction
        });
        
        
        output.linked_systems = await identity_workflows.getLinked_systems({
            transaction
        });
        
        
        output.linked_controls = await identity_workflows.getLinked_controls({
            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.connected_systems,
        as: 'linked_systems',
        required: false,
      },

      {
        model: db.control_requirements,
        as: 'linked_controls',
        required: false,
      },


    ];

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

            
            if (filter.workflow_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'identity_workflows',
                        'workflow_name',
                        filter.workflow_name,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'identity_workflows',
                        'description',
                        filter.description,
                    ),
                };
            }
            
            if (filter.coverage_gap_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'identity_workflows',
                        'coverage_gap_notes',
                        filter.coverage_gap_notes,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.workflow_type) {
                where = {
                    ...where,
                workflow_type: filter.workflow_type,
            };
            }
            
            if (filter.risk_level) {
                where = {
                    ...where,
                risk_level: filter.risk_level,
            };
            }
            
            if (filter.owner_role) {
                where = {
                    ...where,
                owner_role: filter.owner_role,
            };
            }
            
            if (filter.source_trigger_type) {
                where = {
                    ...where,
                source_trigger_type: filter.source_trigger_type,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            
            if (filter.recurrence_type) {
                where = {
                    ...where,
                recurrence_type: filter.recurrence_type,
            };
            }
            


      
      if (filter.organization) {
        const listItems = filter.organization.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationId: {[Op.or]: listItems}
        };
      }
      


      if (filter.linked_systems) {
        const searchTerms = filter.linked_systems.split('|');

        include = [
          {
            model: db.connected_systems,
            as: 'linked_systems_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  system_name: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }

      if (filter.linked_controls) {
        const searchTerms = filter.linked_controls.split('|');

        include = [
          {
            model: db.control_requirements,
            as: 'linked_controls_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  control_code: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


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

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

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

    
};

