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

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

        const map_edges = await db.map_edges.create(
            {
                id: data.id || undefined,
        
        from_node_key: data.from_node_key
        ||
        null
            ,
            
        to_node_key: data.to_node_key
        ||
        null
            ,
            
        relation_type: data.relation_type
        ||
        null
            ,
            
        reasoning: data.reasoning
        ||
        null
            ,
            
        strength: data.strength
        ||
        null
            ,
            
        ai_generated: data.ai_generated
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await map_edges.setMind_map( data.mind_map || null, {
            transaction,
        });
        
        await map_edges.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return map_edges;
    }
    

    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 map_edgesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                from_node_key: item.from_node_key
            ||
            null
            ,
            
                to_node_key: item.to_node_key
            ||
            null
            ,
            
                relation_type: item.relation_type
            ||
            null
            ,
            
                reasoning: item.reasoning
            ||
            null
            ,
            
                strength: item.strength
            ||
            null
            ,
            
                ai_generated: item.ai_generated
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return map_edges;
    }

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


        

        const updatePayload = {};
        
        if (data.from_node_key !== undefined) updatePayload.from_node_key = data.from_node_key;
        
        
        if (data.to_node_key !== undefined) updatePayload.to_node_key = data.to_node_key;
        
        
        if (data.relation_type !== undefined) updatePayload.relation_type = data.relation_type;
        
        
        if (data.reasoning !== undefined) updatePayload.reasoning = data.reasoning;
        
        
        if (data.strength !== undefined) updatePayload.strength = data.strength;
        
        
        if (data.ai_generated !== undefined) updatePayload.ai_generated = data.ai_generated;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.mind_map !== undefined) {
            await map_edges.setMind_map(
              
              data.mind_map,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await map_edges.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return map_edges;
    }

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

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

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


        return map_edges;
    }

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

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

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

        await map_edges.destroy({
            transaction
        });

        return map_edges;
    }

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

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

        if (!map_edges) {
            return map_edges;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.mind_map = await map_edges.getMind_map({
            transaction
        });
        
        
        output.organizations = await map_edges.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.mind_maps,
        as: 'mind_map',
        
        where: filter.mind_map ? {
          [Op.or]: [
            { id: { [Op.in]: filter.mind_map.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.mind_map.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.from_node_key) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'map_edges',
                        'from_node_key',
                        filter.from_node_key,
                    ),
                };
            }
            
            if (filter.to_node_key) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'map_edges',
                        'to_node_key',
                        filter.to_node_key,
                    ),
                };
            }
            
            if (filter.reasoning) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'map_edges',
                        'reasoning',
                        filter.reasoning,
                    ),
                };
            }
            

            
            

            

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

            
            if (filter.relation_type) {
                where = {
                    ...where,
                relation_type: filter.relation_type,
            };
            }
            
            if (filter.strength) {
                where = {
                    ...where,
                strength: filter.strength,
            };
            }
            
            if (filter.ai_generated) {
                where = {
                    ...where,
                ai_generated: filter.ai_generated,
            };
            }
            


      

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

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

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

    
};

