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

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

        const learning_signals = await db.learning_signals.create(
            {
                id: data.id || undefined,
        
        signal_type: data.signal_type
        ||
        null
            ,
            
        signal_at: data.signal_at
        ||
        null
            ,
            
        signal_title: data.signal_title
        ||
        null
            ,
            
        signal_details: data.signal_details
        ||
        null
            ,
            
        confidence_score: data.confidence_score
        ||
        null
            ,
            
        applied_to_brain: data.applied_to_brain
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await learning_signals.setCampaign( data.campaign || null, {
            transaction,
        });
        

        

        

        return learning_signals;
    }
    

    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 learning_signalsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                signal_type: item.signal_type
            ||
            null
            ,
            
                signal_at: item.signal_at
            ||
            null
            ,
            
                signal_title: item.signal_title
            ||
            null
            ,
            
                signal_details: item.signal_details
            ||
            null
            ,
            
                confidence_score: item.confidence_score
            ||
            null
            ,
            
                applied_to_brain: item.applied_to_brain
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return learning_signals;
    }

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

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


        

        const updatePayload = {};
        
        if (data.signal_type !== undefined) updatePayload.signal_type = data.signal_type;
        
        
        if (data.signal_at !== undefined) updatePayload.signal_at = data.signal_at;
        
        
        if (data.signal_title !== undefined) updatePayload.signal_title = data.signal_title;
        
        
        if (data.signal_details !== undefined) updatePayload.signal_details = data.signal_details;
        
        
        if (data.confidence_score !== undefined) updatePayload.confidence_score = data.confidence_score;
        
        
        if (data.applied_to_brain !== undefined) updatePayload.applied_to_brain = data.applied_to_brain;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.campaign !== undefined) {
            await learning_signals.setCampaign(
              
              data.campaign,
              
              { transaction }
            );
        }
        

        
        

        

        return learning_signals;
    }

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

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

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


        return learning_signals;
    }

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

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

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

        await learning_signals.destroy({
            transaction
        });

        return learning_signals;
    }

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

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

        if (!learning_signals) {
            return learning_signals;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.campaign = await learning_signals.getCampaign({
            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.campaigns,
        as: 'campaign',
        
        where: filter.campaign ? {
          [Op.or]: [
            { id: { [Op.in]: filter.campaign.split('|').map(term => Utils.uuid(term)) } },
            {
              campaign_name: {
                [Op.or]: filter.campaign.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.signal_title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'learning_signals',
                        'signal_title',
                        filter.signal_title,
                    ),
                };
            }
            
            if (filter.signal_details) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'learning_signals',
                        'signal_details',
                        filter.signal_details,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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


      



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

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

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

    
};

