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

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

        const proof_packets = await db.proof_packets.create(
            {
                id: data.id || undefined,
        
        packet_name: data.packet_name
        ||
        null
            ,
            
        packet_type: data.packet_type
        ||
        null
            ,
            
        packet_status: data.packet_status
        ||
        null
            ,
            
        readiness_score: data.readiness_score
        ||
        null
            ,
            
        generated_on: data.generated_on
        ||
        null
            ,
            
        due_date: data.due_date
        ||
        null
            ,
            
        summary: data.summary
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await proof_packets.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await proof_packets.setFramework( data.framework || null, {
            transaction,
        });
        
        await proof_packets.setWorkflow( data.workflow || null, {
            transaction,
        });
        
        await proof_packets.setSampled_subject( data.sampled_subject || null, {
            transaction,
        });
        
        await proof_packets.setOwner_user( data.owner_user || null, {
            transaction,
        });
        

        
        await proof_packets.setArtifacts(data.artifacts || [], {
            transaction,
        });
        
        await proof_packets.setMapped_controls(data.mapped_controls || [], {
            transaction,
        });
        

        

        return proof_packets;
    }
    

    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 proof_packetsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                packet_name: item.packet_name
            ||
            null
            ,
            
                packet_type: item.packet_type
            ||
            null
            ,
            
                packet_status: item.packet_status
            ||
            null
            ,
            
                readiness_score: item.readiness_score
            ||
            null
            ,
            
                generated_on: item.generated_on
            ||
            null
            ,
            
                due_date: item.due_date
            ||
            null
            ,
            
                summary: item.summary
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return proof_packets;
    }

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


        

        const updatePayload = {};
        
        if (data.packet_name !== undefined) updatePayload.packet_name = data.packet_name;
        
        
        if (data.packet_type !== undefined) updatePayload.packet_type = data.packet_type;
        
        
        if (data.packet_status !== undefined) updatePayload.packet_status = data.packet_status;
        
        
        if (data.readiness_score !== undefined) updatePayload.readiness_score = data.readiness_score;
        
        
        if (data.generated_on !== undefined) updatePayload.generated_on = data.generated_on;
        
        
        if (data.due_date !== undefined) updatePayload.due_date = data.due_date;
        
        
        if (data.summary !== undefined) updatePayload.summary = data.summary;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.organization !== undefined) {
            await proof_packets.setOrganization(
              
              (globalAccess ? data.organization : currentUser.organization.id),
              
              { transaction }
            );
        }
        
        if (data.framework !== undefined) {
            await proof_packets.setFramework(
              
              data.framework,
              
              { transaction }
            );
        }
        
        if (data.workflow !== undefined) {
            await proof_packets.setWorkflow(
              
              data.workflow,
              
              { transaction }
            );
        }
        
        if (data.sampled_subject !== undefined) {
            await proof_packets.setSampled_subject(
              
              data.sampled_subject,
              
              { transaction }
            );
        }
        
        if (data.owner_user !== undefined) {
            await proof_packets.setOwner_user(
              
              data.owner_user,
              
              { transaction }
            );
        }
        

        
        
        if (data.artifacts !== undefined) {
            await proof_packets.setArtifacts(data.artifacts, { transaction });
        }
        
        if (data.mapped_controls !== undefined) {
            await proof_packets.setMapped_controls(data.mapped_controls, { transaction });
        }
        

        

        return proof_packets;
    }

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

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

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


        return proof_packets;
    }

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

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

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

        await proof_packets.destroy({
            transaction
        });

        return proof_packets;
    }

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

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

        if (!proof_packets) {
            return proof_packets;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.remediation_items_linked_packet = await proof_packets.getRemediation_items_linked_packet({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await proof_packets.getOrganization({
            transaction
        });
        
        
        output.framework = await proof_packets.getFramework({
            transaction
        });
        
        
        output.workflow = await proof_packets.getWorkflow({
            transaction
        });
        
        
        output.sampled_subject = await proof_packets.getSampled_subject({
            transaction
        });
        
        
        output.owner_user = await proof_packets.getOwner_user({
            transaction
        });
        
        
        output.artifacts = await proof_packets.getArtifacts({
            transaction
        });
        
        
        output.mapped_controls = await proof_packets.getMapped_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.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.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.sampled_subjects,
        as: 'sampled_subject',
        
        where: filter.sampled_subject ? {
          [Op.or]: [
            { id: { [Op.in]: filter.sampled_subject.split('|').map(term => Utils.uuid(term)) } },
            {
              display_name: {
                [Op.or]: filter.sampled_subject.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}%` }))
              }
            },
          ]
        } : {},
        
      },


      {
        model: db.artifacts,
        as: 'artifacts',
        required: false,
      },

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


    ];

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

            
            if (filter.packet_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'proof_packets',
                        'packet_name',
                        filter.packet_name,
                    ),
                };
            }
            
            if (filter.summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'proof_packets',
                        'summary',
                        filter.summary,
                    ),
                };
            }
            

            
            

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    generated_on: {
                    ...where.generated_on,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

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


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

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

      

      

      

      


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

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

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

        include = [
          {
            model: db.control_requirements,
            as: 'mapped_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.proof_packets.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(
                        'proof_packets',
                        'packet_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

