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

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

        const article_recommendations = await db.article_recommendations.create(
            {
                id: data.id || undefined,
        
        recommended_at: data.recommended_at
        ||
        null
            ,
            
        reason_type: data.reason_type
        ||
        null
            ,
            
        reason_text: data.reason_text
        ||
        null
            ,
            
        state: data.state
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await article_recommendations.setPatient( data.patient || null, {
            transaction,
        });
        
        await article_recommendations.setArticle( data.article || null, {
            transaction,
        });
        
        await article_recommendations.setAccounts( data.accounts || null, {
            transaction,
        });
        

        

        

        return article_recommendations;
    }
    

    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 article_recommendationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                recommended_at: item.recommended_at
            ||
            null
            ,
            
                reason_type: item.reason_type
            ||
            null
            ,
            
                reason_text: item.reason_text
            ||
            null
            ,
            
                state: item.state
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return article_recommendations;
    }

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


        

        const updatePayload = {};
        
        if (data.recommended_at !== undefined) updatePayload.recommended_at = data.recommended_at;
        
        
        if (data.reason_type !== undefined) updatePayload.reason_type = data.reason_type;
        
        
        if (data.reason_text !== undefined) updatePayload.reason_text = data.reason_text;
        
        
        if (data.state !== undefined) updatePayload.state = data.state;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.patient !== undefined) {
            await article_recommendations.setPatient(
              
              data.patient,
              
              { transaction }
            );
        }
        
        if (data.article !== undefined) {
            await article_recommendations.setArticle(
              
              data.article,
              
              { transaction }
            );
        }
        
        if (data.accounts !== undefined) {
            await article_recommendations.setAccounts(
              
              data.accounts,
              
              { transaction }
            );
        }
        

        
        

        

        return article_recommendations;
    }

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

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

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


        return article_recommendations;
    }

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

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

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

        await article_recommendations.destroy({
            transaction
        });

        return article_recommendations;
    }

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

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

        if (!article_recommendations) {
            return article_recommendations;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.patient = await article_recommendations.getPatient({
            transaction
        });
        
        
        output.article = await article_recommendations.getArticle({
            transaction
        });
        
        
        output.accounts = await article_recommendations.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.patients,
        as: 'patient',
        
        where: filter.patient ? {
          [Op.or]: [
            { id: { [Op.in]: filter.patient.split('|').map(term => Utils.uuid(term)) } },
            {
              last_name: {
                [Op.or]: filter.patient.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            
            if (filter.reason_text) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'article_recommendations',
                        'reason_text',
                        filter.reason_text,
                    ),
                };
            }
            

            
            

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

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

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

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

            
            if (filter.reason_type) {
                where = {
                    ...where,
                reason_type: filter.reason_type,
            };
            }
            
            if (filter.state) {
                where = {
                    ...where,
                state: filter.state,
            };
            }
            


      

      

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

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

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

    
};

