
const db = require('../models');
const FileDBApi = require('./file');
const crypto = require('crypto');
const Utils = require('../utils');



const Sequelize = db.Sequelize;
const Op = Sequelize.Op;

module.exports = class Knowledge_gap_assessmentsDBApi {
    

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

        const knowledge_gap_assessments = await db.knowledge_gap_assessments.create(
            {
                id: data.id || undefined,
        
        assessment_type: data.assessment_type
        ||
        null
            ,
            
        assessed_at: data.assessed_at
        ||
        null
            ,
            
        overall_score: data.overall_score
        ||
        null
            ,
            
        insights_summary: data.insights_summary
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await knowledge_gap_assessments.setOrganization(currentUser.organization.id || null, {
            transaction,
        });
        
        await knowledge_gap_assessments.setUser( data.user || null, {
            transaction,
        });
        

        

        

        return knowledge_gap_assessments;
    }
    

    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 knowledge_gap_assessmentsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                assessment_type: item.assessment_type
            ||
            null
            ,
            
                assessed_at: item.assessed_at
            ||
            null
            ,
            
                overall_score: item.overall_score
            ||
            null
            ,
            
                insights_summary: item.insights_summary
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return knowledge_gap_assessments;
    }

    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 knowledge_gap_assessments = await db.knowledge_gap_assessments.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.assessment_type !== undefined) updatePayload.assessment_type = data.assessment_type;
        
        
        if (data.assessed_at !== undefined) updatePayload.assessed_at = data.assessed_at;
        
        
        if (data.overall_score !== undefined) updatePayload.overall_score = data.overall_score;
        
        
        if (data.insights_summary !== undefined) updatePayload.insights_summary = data.insights_summary;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return knowledge_gap_assessments;
    }

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

        const knowledge_gap_assessments = await db.knowledge_gap_assessments.findAll({
            where: {
                id: {
                    [Op.in]: ids,
                },
            },
            transaction,
        });

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


        return knowledge_gap_assessments;
    }

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

        const knowledge_gap_assessments = await db.knowledge_gap_assessments.findByPk(id, options);

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

        await knowledge_gap_assessments.destroy({
            transaction
        });

        return knowledge_gap_assessments;
    }

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

        const knowledge_gap_assessments = await db.knowledge_gap_assessments.findOne(
            { where },
            { transaction },
        );

        if (!knowledge_gap_assessments) {
            return knowledge_gap_assessments;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.organization = await knowledge_gap_assessments.getOrganization({
            transaction
        });
        
        
        output.user = await knowledge_gap_assessments.getUser({
            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.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.insights_summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'knowledge_gap_assessments',
                        'insights_summary',
                        filter.insights_summary,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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


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

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

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

    
};

