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

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

        const ai_insights = await db.ai_insights.create(
            {
                id: data.id || undefined,
        
        insight_type: data.insight_type
        ||
        null
            ,
            
        severity: data.severity
        ||
        null
            ,
            
        insight_title: data.insight_title
        ||
        null
            ,
            
        insight_summary: data.insight_summary
        ||
        null
            ,
            
        recommendation: data.recommendation
        ||
        null
            ,
            
        generated_at: data.generated_at
        ||
        null
            ,
            
        valid_until: data.valid_until
        ||
        null
            ,
            
        is_acknowledged: data.is_acknowledged
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await ai_insights.setTenant( data.tenant || null, {
            transaction,
        });
        
        await ai_insights.setRelated_user( data.related_user || null, {
            transaction,
        });
        
        await ai_insights.setRelated_product( data.related_product || null, {
            transaction,
        });
        
        await ai_insights.setRelated_warehouse( data.related_warehouse || null, {
            transaction,
        });
        
        await ai_insights.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return ai_insights;
    }
    

    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_insightsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                insight_type: item.insight_type
            ||
            null
            ,
            
                severity: item.severity
            ||
            null
            ,
            
                insight_title: item.insight_title
            ||
            null
            ,
            
                insight_summary: item.insight_summary
            ||
            null
            ,
            
                recommendation: item.recommendation
            ||
            null
            ,
            
                generated_at: item.generated_at
            ||
            null
            ,
            
                valid_until: item.valid_until
            ||
            null
            ,
            
                is_acknowledged: item.is_acknowledged
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return ai_insights;
    }

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


        

        const updatePayload = {};
        
        if (data.insight_type !== undefined) updatePayload.insight_type = data.insight_type;
        
        
        if (data.severity !== undefined) updatePayload.severity = data.severity;
        
        
        if (data.insight_title !== undefined) updatePayload.insight_title = data.insight_title;
        
        
        if (data.insight_summary !== undefined) updatePayload.insight_summary = data.insight_summary;
        
        
        if (data.recommendation !== undefined) updatePayload.recommendation = data.recommendation;
        
        
        if (data.generated_at !== undefined) updatePayload.generated_at = data.generated_at;
        
        
        if (data.valid_until !== undefined) updatePayload.valid_until = data.valid_until;
        
        
        if (data.is_acknowledged !== undefined) updatePayload.is_acknowledged = data.is_acknowledged;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.tenant !== undefined) {
            await ai_insights.setTenant(
              
              data.tenant,
              
              { transaction }
            );
        }
        
        if (data.related_user !== undefined) {
            await ai_insights.setRelated_user(
              
              data.related_user,
              
              { transaction }
            );
        }
        
        if (data.related_product !== undefined) {
            await ai_insights.setRelated_product(
              
              data.related_product,
              
              { transaction }
            );
        }
        
        if (data.related_warehouse !== undefined) {
            await ai_insights.setRelated_warehouse(
              
              data.related_warehouse,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await ai_insights.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return ai_insights;
    }

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

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

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


        return ai_insights;
    }

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

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

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

        await ai_insights.destroy({
            transaction
        });

        return ai_insights;
    }

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

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

        if (!ai_insights) {
            return ai_insights;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.tenant = await ai_insights.getTenant({
            transaction
        });
        
        
        output.related_user = await ai_insights.getRelated_user({
            transaction
        });
        
        
        output.related_product = await ai_insights.getRelated_product({
            transaction
        });
        
        
        output.related_warehouse = await ai_insights.getRelated_warehouse({
            transaction
        });
        
        
        output.organizations = await ai_insights.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.tenants,
        as: 'tenant',
        
        where: filter.tenant ? {
          [Op.or]: [
            { id: { [Op.in]: filter.tenant.split('|').map(term => Utils.uuid(term)) } },
            {
              tenant_name: {
                [Op.or]: filter.tenant.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

      {
        model: db.warehouses,
        as: 'related_warehouse',
        
        where: filter.related_warehouse ? {
          [Op.or]: [
            { id: { [Op.in]: filter.related_warehouse.split('|').map(term => Utils.uuid(term)) } },
            {
              warehouse_name: {
                [Op.or]: filter.related_warehouse.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.insight_title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ai_insights',
                        'insight_title',
                        filter.insight_title,
                    ),
                };
            }
            
            if (filter.insight_summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ai_insights',
                        'insight_summary',
                        filter.insight_summary,
                    ),
                };
            }
            
            if (filter.recommendation) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'ai_insights',
                        'recommendation',
                        filter.recommendation,
                    ),
                };
            }
            

            
            

            
            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.valid_untilRange) {
                const [start, end] = filter.valid_untilRange;

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

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

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

            
            if (filter.insight_type) {
                where = {
                    ...where,
                insight_type: filter.insight_type,
            };
            }
            
            if (filter.severity) {
                where = {
                    ...where,
                severity: filter.severity,
            };
            }
            
            if (filter.is_acknowledged) {
                where = {
                    ...where,
                is_acknowledged: filter.is_acknowledged,
            };
            }
            


      

      

      

      

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

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

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

    
};

