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

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

        const scientific_articles = await db.scientific_articles.create(
            {
                id: data.id || undefined,
        
        title_text: data.title_text
        ||
        null
            ,
            
        abstract_text: data.abstract_text
        ||
        null
            ,
            
        journal: data.journal
        ||
        null
            ,
            
        published_at: data.published_at
        ||
        null
            ,
            
        doi: data.doi
        ||
        null
            ,
            
        url: data.url
        ||
        null
            ,
            
        keywords: data.keywords
        ||
        null
            ,
            
        validation_status: data.validation_status
        ||
        null
            ,
            
        validation_notes: data.validation_notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await scientific_articles.setValidated_by_user( data.validated_by_user || null, {
            transaction,
        });
        
        await scientific_articles.setAccounts( data.accounts || null, {
            transaction,
        });
        

        

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

        return scientific_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 scientific_articlesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title_text: item.title_text
            ||
            null
            ,
            
                abstract_text: item.abstract_text
            ||
            null
            ,
            
                journal: item.journal
            ||
            null
            ,
            
                published_at: item.published_at
            ||
            null
            ,
            
                doi: item.doi
            ||
            null
            ,
            
                url: item.url
            ||
            null
            ,
            
                keywords: item.keywords
            ||
            null
            ,
            
                validation_status: item.validation_status
            ||
            null
            ,
            
                validation_notes: item.validation_notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return scientific_articles;
    }

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


        

        const updatePayload = {};
        
        if (data.title_text !== undefined) updatePayload.title_text = data.title_text;
        
        
        if (data.abstract_text !== undefined) updatePayload.abstract_text = data.abstract_text;
        
        
        if (data.journal !== undefined) updatePayload.journal = data.journal;
        
        
        if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
        
        
        if (data.doi !== undefined) updatePayload.doi = data.doi;
        
        
        if (data.url !== undefined) updatePayload.url = data.url;
        
        
        if (data.keywords !== undefined) updatePayload.keywords = data.keywords;
        
        
        if (data.validation_status !== undefined) updatePayload.validation_status = data.validation_status;
        
        
        if (data.validation_notes !== undefined) updatePayload.validation_notes = data.validation_notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.validated_by_user !== undefined) {
            await scientific_articles.setValidated_by_user(
              
              data.validated_by_user,
              
              { transaction }
            );
        }
        
        if (data.accounts !== undefined) {
            await scientific_articles.setAccounts(
              
              data.accounts,
              
              { transaction }
            );
        }
        

        
        

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

        return scientific_articles;
    }

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

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

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


        return scientific_articles;
    }

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

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

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

        await scientific_articles.destroy({
            transaction
        });

        return scientific_articles;
    }

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

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

        if (!scientific_articles) {
            return scientific_articles;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.article_recommendations_article = await scientific_articles.getArticle_recommendations_article({
            transaction
        });
        
        
        
        
        
        output.validated_by_user = await scientific_articles.getValidated_by_user({
            transaction
        });
        
        
        output.pdf_file = await scientific_articles.getPdf_file({
            transaction
        });
        
        
        output.accounts = await scientific_articles.getAccounts({
            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 userAccounts = (user && user.accounts?.id) || null;
        

        
        if (userAccounts) {
            if (options?.currentUser?.accountsId) {
                where.accountsId = options.currentUser.accountsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

      {
        model: db.accounts,
        as: 'accounts',
        
      },



      {
        model: db.file,
        as: 'pdf_file',
      },

    ];

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

            
            if (filter.title_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'scientific_articles',
                        'title_text',
                        filter.title_text,
                    ),
                };
            }
            
            if (filter.abstract_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'scientific_articles',
                        'abstract_text',
                        filter.abstract_text,
                    ),
                };
            }
            
            if (filter.journal) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'scientific_articles',
                        'journal',
                        filter.journal,
                    ),
                };
            }
            
            if (filter.doi) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'scientific_articles',
                        'doi',
                        filter.doi,
                    ),
                };
            }
            
            if (filter.url) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'scientific_articles',
                        'url',
                        filter.url,
                    ),
                };
            }
            
            if (filter.keywords) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'scientific_articles',
                        'keywords',
                        filter.keywords,
                    ),
                };
            }
            
            if (filter.validation_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'scientific_articles',
                        'validation_notes',
                        filter.validation_notes,
                    ),
                };
            }
            

            
            

            
            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.validation_status) {
                where = {
                    ...where,
                validation_status: filter.validation_status,
            };
            }
            


      

      
      if (filter.accounts) {
        const listItems = filter.accounts.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          accountsId: {[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.accountsId;
        }
        

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

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

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

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

    
};

