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

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

        const news_articles = await db.news_articles.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        publisher: data.publisher
        ||
        null
            ,
            
        published_at: data.published_at
        ||
        null
            ,
            
        category: data.category
        ||
        null
            ,
            
        url: data.url
        ||
        null
            ,
            
        summary: data.summary
        ||
        null
            ,
            
        content: data.content
        ||
        null
            ,
            
        sentiment: data.sentiment
        ||
        null
            ,
            
        source: data.source
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.news_articles.getTableName(),
                belongsToColumn: 'cover_images',
                belongsToId: news_articles.id,
            },
            data.cover_images,
            options,
        );
        

        return news_articles;
    }
    

    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 news_articlesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                publisher: item.publisher
            ||
            null
            ,
            
                published_at: item.published_at
            ||
            null
            ,
            
                category: item.category
            ||
            null
            ,
            
                url: item.url
            ||
            null
            ,
            
                summary: item.summary
            ||
            null
            ,
            
                content: item.content
            ||
            null
            ,
            
                sentiment: item.sentiment
            ||
            null
            ,
            
                source: item.source
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < news_articles.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.news_articles.getTableName(),
                    belongsToColumn: 'cover_images',
                    belongsToId: news_articles[i].id,
                },
                data[i].cover_images,
                options,
            );
        }
        

        return news_articles;
    }

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

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.publisher !== undefined) updatePayload.publisher = data.publisher;
        
        
        if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
        
        
        if (data.category !== undefined) updatePayload.category = data.category;
        
        
        if (data.url !== undefined) updatePayload.url = data.url;
        
        
        if (data.summary !== undefined) updatePayload.summary = data.summary;
        
        
        if (data.content !== undefined) updatePayload.content = data.content;
        
        
        if (data.sentiment !== undefined) updatePayload.sentiment = data.sentiment;
        
        
        if (data.source !== undefined) updatePayload.source = data.source;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.news_articles.getTableName(),
                belongsToColumn: 'cover_images',
                belongsToId: news_articles.id,
            },
            data.cover_images,
            options,
        );
        

        return news_articles;
    }

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

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

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


        return news_articles;
    }

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

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

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

        await news_articles.destroy({
            transaction
        });

        return news_articles;
    }

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

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

        if (!news_articles) {
            return news_articles;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        output.news_article_symbols_news_article = await news_articles.getNews_article_symbols_news_article({
            transaction
        });
        
        
        output.article_bookmarks_news_article = await news_articles.getArticle_bookmarks_news_article({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.cover_images = await news_articles.getCover_images({
            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.file,
        as: 'cover_images',
      },

    ];

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

            
            if (filter.title) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'news_articles',
                        'title',
                        filter.title,
                    ),
                };
            }
            
            if (filter.publisher) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'news_articles',
                        'publisher',
                        filter.publisher,
                    ),
                };
            }
            
            if (filter.url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'news_articles',
                        'url',
                        filter.url,
                    ),
                };
            }
            
            if (filter.summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'news_articles',
                        'summary',
                        filter.summary,
                    ),
                };
            }
            
            if (filter.content) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'news_articles',
                        'content',
                        filter.content,
                    ),
                };
            }
            
            if (filter.source) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'news_articles',
                        'source',
                        filter.source,
                    ),
                };
            }
            

            
            

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

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

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

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

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




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

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

    
};

