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

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

        const knowledge_graph_items = await db.knowledge_graph_items.create(
            {
                id: data.id || undefined,
        
        item_type: data.item_type
        ||
        null
            ,
            
        title: data.title
        ||
        null
            ,
            
        details: data.details
        ||
        null
            ,
            
        importance: data.importance
        ||
        null
            ,
            
        item_status: data.item_status
        ||
        null
            ,
            
        captured_at: data.captured_at
        ||
        null
            ,
            
        due_at: data.due_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await knowledge_graph_items.setAi_companion_session( data.ai_companion_session || null, {
            transaction,
        });
        
        await knowledge_graph_items.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return knowledge_graph_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 knowledge_graph_itemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                item_type: item.item_type
            ||
            null
            ,
            
                title: item.title
            ||
            null
            ,
            
                details: item.details
            ||
            null
            ,
            
                importance: item.importance
            ||
            null
            ,
            
                item_status: item.item_status
            ||
            null
            ,
            
                captured_at: item.captured_at
            ||
            null
            ,
            
                due_at: item.due_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

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


        

        const updatePayload = {};
        
        if (data.item_type !== undefined) updatePayload.item_type = data.item_type;
        
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.details !== undefined) updatePayload.details = data.details;
        
        
        if (data.importance !== undefined) updatePayload.importance = data.importance;
        
        
        if (data.item_status !== undefined) updatePayload.item_status = data.item_status;
        
        
        if (data.captured_at !== undefined) updatePayload.captured_at = data.captured_at;
        
        
        if (data.due_at !== undefined) updatePayload.due_at = data.due_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.ai_companion_session !== undefined) {
            await knowledge_graph_items.setAi_companion_session(
              
              data.ai_companion_session,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await knowledge_graph_items.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return knowledge_graph_items;
    }

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

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

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


        return knowledge_graph_items;
    }

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

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

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

        await knowledge_graph_items.destroy({
            transaction
        });

        return knowledge_graph_items;
    }

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

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

        if (!knowledge_graph_items) {
            return knowledge_graph_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tasks_knowledge_graph_item = await knowledge_graph_items.getTasks_knowledge_graph_item({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.ai_companion_session = await knowledge_graph_items.getAi_companion_session({
            transaction
        });
        
        
        output.organizations = await knowledge_graph_items.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.ai_companion_sessions,
        as: 'ai_companion_session',
        
        where: filter.ai_companion_session ? {
          [Op.or]: [
            { id: { [Op.in]: filter.ai_companion_session.split('|').map(term => Utils.uuid(term)) } },
            {
              companion_status: {
                [Op.or]: filter.ai_companion_session.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.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'knowledge_graph_items',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.details) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'knowledge_graph_items',
                        'details',
                        filter.details,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.item_type) {
                where = {
                    ...where,
                item_type: filter.item_type,
            };
            }
            
            if (filter.importance) {
                where = {
                    ...where,
                importance: filter.importance,
            };
            }
            
            if (filter.item_status) {
                where = {
                    ...where,
                item_status: filter.item_status,
            };
            }
            


      

      
      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.knowledge_graph_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(
                        'knowledge_graph_items',
                        'title',
                        query,
                    ),
                ],
            };
        }

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

    
};

