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

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

        const forum_threads = await db.forum_threads.create(
            {
                id: data.id || undefined,
        
        thread_title: data.thread_title
        ||
        null
            ,
            
        thread_body: data.thread_body
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        created_on: data.created_on
        ||
        null
            ,
            
        last_activity_at: data.last_activity_at
        ||
        null
            ,
            
        upvotes_count: data.upvotes_count
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await forum_threads.setSpace( data.space || null, {
            transaction,
        });
        
        await forum_threads.setAuthor( data.author || null, {
            transaction,
        });
        
        await forum_threads.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return forum_threads;
    }
    

    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 forum_threadsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                thread_title: item.thread_title
            ||
            null
            ,
            
                thread_body: item.thread_body
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                created_on: item.created_on
            ||
            null
            ,
            
                last_activity_at: item.last_activity_at
            ||
            null
            ,
            
                upvotes_count: item.upvotes_count
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return forum_threads;
    }

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


        

        const updatePayload = {};
        
        if (data.thread_title !== undefined) updatePayload.thread_title = data.thread_title;
        
        
        if (data.thread_body !== undefined) updatePayload.thread_body = data.thread_body;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.created_on !== undefined) updatePayload.created_on = data.created_on;
        
        
        if (data.last_activity_at !== undefined) updatePayload.last_activity_at = data.last_activity_at;
        
        
        if (data.upvotes_count !== undefined) updatePayload.upvotes_count = data.upvotes_count;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.space !== undefined) {
            await forum_threads.setSpace(
              
              data.space,
              
              { transaction }
            );
        }
        
        if (data.author !== undefined) {
            await forum_threads.setAuthor(
              
              data.author,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await forum_threads.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return forum_threads;
    }

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

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

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


        return forum_threads;
    }

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

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

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

        await forum_threads.destroy({
            transaction
        });

        return forum_threads;
    }

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

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

        if (!forum_threads) {
            return forum_threads;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.forum_posts_thread = await forum_threads.getForum_posts_thread({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.space = await forum_threads.getSpace({
            transaction
        });
        
        
        output.author = await forum_threads.getAuthor({
            transaction
        });
        
        
        output.organizations = await forum_threads.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.forum_spaces,
        as: 'space',
        
        where: filter.space ? {
          [Op.or]: [
            { id: { [Op.in]: filter.space.split('|').map(term => Utils.uuid(term)) } },
            {
              space_name: {
                [Op.or]: filter.space.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

            
            

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

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

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

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

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

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

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

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

            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.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.forum_threads.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(
                        'forum_threads',
                        'thread_title',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

