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

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

        const ai_recommendations = await db.ai_recommendations.create(
            {
                id: data.id || undefined,
        
        recommendation_type: data.recommendation_type
        ||
        null
            ,
            
        score: data.score
        ||
        null
            ,
            
        reason_text: data.reason_text
        ||
        null
            ,
            
        generated_at: data.generated_at
        ||
        null
            ,
            
        expires_at: data.expires_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await ai_recommendations.setUser( data.user || null, {
            transaction,
        });
        
        await ai_recommendations.setPost( data.post || null, {
            transaction,
        });
        
        await ai_recommendations.setSuggested_user( data.suggested_user || null, {
            transaction,
        });
        
        await ai_recommendations.setGroup( data.group || null, {
            transaction,
        });
        
        await ai_recommendations.setHashtag( data.hashtag || null, {
            transaction,
        });
        

        

        

        return ai_recommendations;
    }
    

    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 ai_recommendationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                recommendation_type: item.recommendation_type
            ||
            null
            ,
            
                score: item.score
            ||
            null
            ,
            
                reason_text: item.reason_text
            ||
            null
            ,
            
                generated_at: item.generated_at
            ||
            null
            ,
            
                expires_at: item.expires_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return ai_recommendations;
    }

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

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


        

        const updatePayload = {};
        
        if (data.recommendation_type !== undefined) updatePayload.recommendation_type = data.recommendation_type;
        
        
        if (data.score !== undefined) updatePayload.score = data.score;
        
        
        if (data.reason_text !== undefined) updatePayload.reason_text = data.reason_text;
        
        
        if (data.generated_at !== undefined) updatePayload.generated_at = data.generated_at;
        
        
        if (data.expires_at !== undefined) updatePayload.expires_at = data.expires_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await ai_recommendations.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.post !== undefined) {
            await ai_recommendations.setPost(
              
              data.post,
              
              { transaction }
            );
        }
        
        if (data.suggested_user !== undefined) {
            await ai_recommendations.setSuggested_user(
              
              data.suggested_user,
              
              { transaction }
            );
        }
        
        if (data.group !== undefined) {
            await ai_recommendations.setGroup(
              
              data.group,
              
              { transaction }
            );
        }
        
        if (data.hashtag !== undefined) {
            await ai_recommendations.setHashtag(
              
              data.hashtag,
              
              { transaction }
            );
        }
        

        
        

        

        return ai_recommendations;
    }

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

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

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


        return ai_recommendations;
    }

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

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

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

        await ai_recommendations.destroy({
            transaction
        });

        return ai_recommendations;
    }

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

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

        if (!ai_recommendations) {
            return ai_recommendations;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await ai_recommendations.getUser({
            transaction
        });
        
        
        output.post = await ai_recommendations.getPost({
            transaction
        });
        
        
        output.suggested_user = await ai_recommendations.getSuggested_user({
            transaction
        });
        
        
        output.group = await ai_recommendations.getGroup({
            transaction
        });
        
        
        output.hashtag = await ai_recommendations.getHashtag({
            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: '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}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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

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



    ];

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

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

            
            

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

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

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

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

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

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

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

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

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


      

      

      

      

      



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

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

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

    
};

