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

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

        const remediation_items = await db.remediation_items.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        severity: data.severity
        ||
        null
            ,
            
        category: data.category
        ||
        null
            ,
            
        due_date: data.due_date
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        remediation_plan: data.remediation_plan
        ||
        null
            ,
            
        completed_at: data.completed_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await remediation_items.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await remediation_items.setLinked_workflow( data.linked_workflow || null, {
            transaction,
        });
        
        await remediation_items.setLinked_control_requirement( data.linked_control_requirement || null, {
            transaction,
        });
        
        await remediation_items.setLinked_artifact( data.linked_artifact || null, {
            transaction,
        });
        
        await remediation_items.setLinked_packet( data.linked_packet || null, {
            transaction,
        });
        
        await remediation_items.setOwner_user( data.owner_user || null, {
            transaction,
        });
        

        

        

        return remediation_items;
    }
    

    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 remediation_itemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                severity: item.severity
            ||
            null
            ,
            
                category: item.category
            ||
            null
            ,
            
                due_date: item.due_date
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                remediation_plan: item.remediation_plan
            ||
            null
            ,
            
                completed_at: item.completed_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return remediation_items;
    }

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.severity !== undefined) updatePayload.severity = data.severity;
        
        
        if (data.category !== undefined) updatePayload.category = data.category;
        
        
        if (data.due_date !== undefined) updatePayload.due_date = data.due_date;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.remediation_plan !== undefined) updatePayload.remediation_plan = data.remediation_plan;
        
        
        if (data.completed_at !== undefined) updatePayload.completed_at = data.completed_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await remediation_items.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.linked_workflow !== undefined) {
            await remediation_items.setLinked_workflow(
              
              data.linked_workflow,
              
              { transaction }
            );
        }
        
        if (data.linked_control_requirement !== undefined) {
            await remediation_items.setLinked_control_requirement(
              
              data.linked_control_requirement,
              
              { transaction }
            );
        }
        
        if (data.linked_artifact !== undefined) {
            await remediation_items.setLinked_artifact(
              
              data.linked_artifact,
              
              { transaction }
            );
        }
        
        if (data.linked_packet !== undefined) {
            await remediation_items.setLinked_packet(
              
              data.linked_packet,
              
              { transaction }
            );
        }
        
        if (data.owner_user !== undefined) {
            await remediation_items.setOwner_user(
              
              data.owner_user,
              
              { transaction }
            );
        }
        

        
        

        

        return remediation_items;
    }

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

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

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


        return remediation_items;
    }

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

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

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

        await remediation_items.destroy({
            transaction
        });

        return remediation_items;
    }

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

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

        if (!remediation_items) {
            return remediation_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await remediation_items.getOrganization({
            transaction
        });
        
        
        output.linked_workflow = await remediation_items.getLinked_workflow({
            transaction
        });
        
        
        output.linked_control_requirement = await remediation_items.getLinked_control_requirement({
            transaction
        });
        
        
        output.linked_artifact = await remediation_items.getLinked_artifact({
            transaction
        });
        
        
        output.linked_packet = await remediation_items.getLinked_packet({
            transaction
        });
        
        
        output.owner_user = await remediation_items.getOwner_user({
            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: 'linked_workflow',
        
        where: filter.linked_workflow ? {
          [Op.or]: [
            { id: { [Op.in]: filter.linked_workflow.split('|').map(term => Utils.uuid(term)) } },
            {
              workflow_name: {
                [Op.or]: filter.linked_workflow.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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

      {
        model: db.users,
        as: 'owner_user',
        
        where: filter.owner_user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.owner_user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.owner_user.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(
                        'remediation_items',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.description) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'remediation_items',
                        'description',
                        filter.description,
                    ),
                };
            }
            
            if (filter.remediation_plan) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'remediation_items',
                        'remediation_plan',
                        filter.remediation_plan,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.severity) {
                where = {
                    ...where,
                severity: filter.severity,
            };
            }
            
            if (filter.category) {
                where = {
                    ...where,
                category: filter.category,
            };
            }
            
            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.remediation_items.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(
                        'remediation_items',
                        'title',
                        query,
                    ),
                ],
            };
        }

        const records = await db.remediation_items.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,
        }));
    }

    
};

