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

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

        const ai_insight_items = await db.ai_insight_items.create(
            {
                id: data.id || undefined,
        
        category: data.category
        ||
        null
            ,
            
        severity: data.severity
        ||
        null
            ,
            
        title: data.title
        ||
        null
            ,
            
        detail: data.detail
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await ai_insight_items.setAi_insight_run( data.ai_insight_run || null, {
            transaction,
        });
        

        
        await ai_insight_items.setRelated_trades(data.related_trades || [], {
            transaction,
        });
        

        

        return ai_insight_items;
    }
    

    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_insight_itemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                category: item.category
            ||
            null
            ,
            
                severity: item.severity
            ||
            null
            ,
            
                title: item.title
            ||
            null
            ,
            
                detail: item.detail
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return ai_insight_items;
    }

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

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


        

        const updatePayload = {};
        
        if (data.category !== undefined) updatePayload.category = data.category;
        
        
        if (data.severity !== undefined) updatePayload.severity = data.severity;
        
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.detail !== undefined) updatePayload.detail = data.detail;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.ai_insight_run !== undefined) {
            await ai_insight_items.setAi_insight_run(
              
              data.ai_insight_run,
              
              { transaction }
            );
        }
        

        
        
        if (data.related_trades !== undefined) {
            await ai_insight_items.setRelated_trades(data.related_trades, { transaction });
        }
        

        

        return ai_insight_items;
    }

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

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

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


        return ai_insight_items;
    }

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

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

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

        await ai_insight_items.destroy({
            transaction
        });

        return ai_insight_items;
    }

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

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

        if (!ai_insight_items) {
            return ai_insight_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.ai_insight_run = await ai_insight_items.getAi_insight_run({
            transaction
        });
        
        
        output.related_trades = await ai_insight_items.getRelated_trades({
            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.ai_insight_runs,
        as: 'ai_insight_run',
        
        where: filter.ai_insight_run ? {
          [Op.or]: [
            { id: { [Op.in]: filter.ai_insight_run.split('|').map(term => Utils.uuid(term)) } },
            {
              output_summary: {
                [Op.or]: filter.ai_insight_run.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },


      {
        model: db.trades,
        as: 'related_trades',
        required: false,
      },


    ];

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

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

            
            

            

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

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


      


      if (filter.related_trades) {
        const searchTerms = filter.related_trades.split('|');

        include = [
          {
            model: db.trades,
            as: 'related_trades_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  notes: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


            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_insight_items.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_insight_items',
                        'title',
                        query,
                    ),
                ],
            };
        }

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

    
};

