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

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

        const assistant_threads = await db.assistant_threads.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        thread_scope: data.thread_scope
        ||
        null
            ,
            
        is_pinned: data.is_pinned
        ||
        false
        
            ,
            
        last_activity_at: data.last_activity_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await assistant_threads.setOwner( data.owner || null, {
            transaction,
        });
        
        await assistant_threads.setMatter( data.matter || null, {
            transaction,
        });
        

        

        

        return assistant_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 assistant_threadsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                thread_scope: item.thread_scope
            ||
            null
            ,
            
                is_pinned: item.is_pinned
            ||
            false
        
            ,
            
                last_activity_at: item.last_activity_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return assistant_threads;
    }

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

        const assistant_threads = await db.assistant_threads.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.thread_scope !== undefined) updatePayload.thread_scope = data.thread_scope;
        
        
        if (data.is_pinned !== undefined) updatePayload.is_pinned = data.is_pinned;
        
        
        if (data.last_activity_at !== undefined) updatePayload.last_activity_at = data.last_activity_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.owner !== undefined) {
            await assistant_threads.setOwner(
              
              data.owner,
              
              { transaction }
            );
        }
        
        if (data.matter !== undefined) {
            await assistant_threads.setMatter(
              
              data.matter,
              
              { transaction }
            );
        }
        

        
        

        

        return assistant_threads;
    }

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

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

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


        return assistant_threads;
    }

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

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

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

        await assistant_threads.destroy({
            transaction
        });

        return assistant_threads;
    }

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

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

        if (!assistant_threads) {
            return assistant_threads;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        output.assistant_messages_thread = await assistant_threads.getAssistant_messages_thread({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.owner = await assistant_threads.getOwner({
            transaction
        });
        
        
        output.matter = await assistant_threads.getMatter({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

      {
        model: db.users,
        as: 'owner',
        
        where: filter.owner ? {
          [Op.or]: [
            { id: { [Op.in]: filter.owner.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.owner.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.matters,
        as: 'matter',
        
        where: filter.matter ? {
          [Op.or]: [
            { id: { [Op.in]: filter.matter.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.matter.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

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

            
            

            
            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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

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


      

      



            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,
                        },
                    };
                }
            }
        }
        

        

        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.assistant_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, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'assistant_threads',
                        'title',
                        query,
                    ),
                ],
            };
        }

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

    
};

