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

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

        const external_signals = await db.external_signals.create(
            {
                id: data.id || undefined,
        
        source: data.source
        ||
        null
            ,
            
        signal_type: data.signal_type
        ||
        null
            ,
            
        title: data.title
        ||
        null
            ,
            
        summary: data.summary
        ||
        null
            ,
            
        source_url: data.source_url
        ||
        null
            ,
            
        signal_score: data.signal_score
        ||
        null
            ,
            
        signal_at: data.signal_at
        ||
        null
            ,
            
        is_verified: data.is_verified
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await external_signals.setUser( data.user || null, {
            transaction,
        });
        
        await external_signals.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return external_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 external_signalsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                source: item.source
            ||
            null
            ,
            
                signal_type: item.signal_type
            ||
            null
            ,
            
                title: item.title
            ||
            null
            ,
            
                summary: item.summary
            ||
            null
            ,
            
                source_url: item.source_url
            ||
            null
            ,
            
                signal_score: item.signal_score
            ||
            null
            ,
            
                signal_at: item.signal_at
            ||
            null
            ,
            
                is_verified: item.is_verified
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return external_signals;
    }

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


        

        const updatePayload = {};
        
        if (data.source !== undefined) updatePayload.source = data.source;
        
        
        if (data.signal_type !== undefined) updatePayload.signal_type = data.signal_type;
        
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.summary !== undefined) updatePayload.summary = data.summary;
        
        
        if (data.source_url !== undefined) updatePayload.source_url = data.source_url;
        
        
        if (data.signal_score !== undefined) updatePayload.signal_score = data.signal_score;
        
        
        if (data.signal_at !== undefined) updatePayload.signal_at = data.signal_at;
        
        
        if (data.is_verified !== undefined) updatePayload.is_verified = data.is_verified;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await external_signals.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await external_signals.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return external_signals;
    }

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

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

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


        return external_signals;
    }

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

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

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

        await external_signals.destroy({
            transaction
        });

        return external_signals;
    }

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

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

        if (!external_signals) {
            return external_signals;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await external_signals.getUser({
            transaction
        });
        
        
        output.organizations = await external_signals.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.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.organizations,
        as: 'organizations',
        
      },



    ];

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

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

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    signal_score: {
                    ...where.signal_score,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

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


      

      
      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.external_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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

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

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

    
};

