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

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

        const control_requirements = await db.control_requirements.create(
            {
                id: data.id || undefined,
        
        control_code: data.control_code
        ||
        null
            ,
            
        control_family: data.control_family
        ||
        null
            ,
            
        control_title: data.control_title
        ||
        null
            ,
            
        control_description: data.control_description
        ||
        null
            ,
            
        evidence_expectation_summary: data.evidence_expectation_summary
        ||
        null
            ,
            
        active_flag: data.active_flag
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await control_requirements.setFramework( data.framework || null, {
            transaction,
        });
        
        await control_requirements.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return control_requirements;
    }
    

    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 control_requirementsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                control_code: item.control_code
            ||
            null
            ,
            
                control_family: item.control_family
            ||
            null
            ,
            
                control_title: item.control_title
            ||
            null
            ,
            
                control_description: item.control_description
            ||
            null
            ,
            
                evidence_expectation_summary: item.evidence_expectation_summary
            ||
            null
            ,
            
                active_flag: item.active_flag
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return control_requirements;
    }

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


        

        const updatePayload = {};
        
        if (data.control_code !== undefined) updatePayload.control_code = data.control_code;
        
        
        if (data.control_family !== undefined) updatePayload.control_family = data.control_family;
        
        
        if (data.control_title !== undefined) updatePayload.control_title = data.control_title;
        
        
        if (data.control_description !== undefined) updatePayload.control_description = data.control_description;
        
        
        if (data.evidence_expectation_summary !== undefined) updatePayload.evidence_expectation_summary = data.evidence_expectation_summary;
        
        
        if (data.active_flag !== undefined) updatePayload.active_flag = data.active_flag;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.framework !== undefined) {
            await control_requirements.setFramework(
              
              data.framework,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await control_requirements.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return control_requirements;
    }

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

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

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


        return control_requirements;
    }

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

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

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

        await control_requirements.destroy({
            transaction
        });

        return control_requirements;
    }

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

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

        if (!control_requirements) {
            return control_requirements;
        }

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

        
        
        
        
        
        
        
        
        
        
        output.evidence_models_control_requirement = await control_requirements.getEvidence_models_control_requirement({
            transaction
        });
        
        
        
        
        
        output.remediation_items_linked_control_requirement = await control_requirements.getRemediation_items_linked_control_requirement({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        output.framework = await control_requirements.getFramework({
            transaction
        });
        
        
        output.organizations = await control_requirements.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.control_frameworks,
        as: 'framework',
        
        where: filter.framework ? {
          [Op.or]: [
            { id: { [Op.in]: filter.framework.split('|').map(term => Utils.uuid(term)) } },
            {
              framework_name: {
                [Op.or]: filter.framework.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.control_code) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'control_requirements',
                        'control_code',
                        filter.control_code,
                    ),
                };
            }
            
            if (filter.control_family) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'control_requirements',
                        'control_family',
                        filter.control_family,
                    ),
                };
            }
            
            if (filter.control_title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'control_requirements',
                        'control_title',
                        filter.control_title,
                    ),
                };
            }
            
            if (filter.control_description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'control_requirements',
                        'control_description',
                        filter.control_description,
                    ),
                };
            }
            
            if (filter.evidence_expectation_summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'control_requirements',
                        'evidence_expectation_summary',
                        filter.evidence_expectation_summary,
                    ),
                };
            }
            

            
            

            

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

            
            if (filter.active_flag) {
                where = {
                    ...where,
                active_flag: filter.active_flag,
            };
            }
            


      

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

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

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

    
};

