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

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

        const supplement_evidence_items = await db.supplement_evidence_items.create(
            {
                id: data.id || undefined,
        
        supplement_name: data.supplement_name
        ||
        null
            ,
            
        evidence_rating: data.evidence_rating
        ||
        null
            ,
            
        summary: data.summary
        ||
        null
            ,
            
        mechanism: data.mechanism
        ||
        null
            ,
            
        benefits: data.benefits
        ||
        null
            ,
            
        dosing_range: data.dosing_range
        ||
        null
            ,
            
        timing_recommendations: data.timing_recommendations
        ||
        null
            ,
            
        interactions: data.interactions
        ||
        null
            ,
            
        side_effects: data.side_effects
        ||
        null
            ,
            
        avoid_who: data.avoid_who
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return supplement_evidence_items;
    }
    

    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 supplement_evidence_itemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                supplement_name: item.supplement_name
            ||
            null
            ,
            
                evidence_rating: item.evidence_rating
            ||
            null
            ,
            
                summary: item.summary
            ||
            null
            ,
            
                mechanism: item.mechanism
            ||
            null
            ,
            
                benefits: item.benefits
            ||
            null
            ,
            
                dosing_range: item.dosing_range
            ||
            null
            ,
            
                timing_recommendations: item.timing_recommendations
            ||
            null
            ,
            
                interactions: item.interactions
            ||
            null
            ,
            
                side_effects: item.side_effects
            ||
            null
            ,
            
                avoid_who: item.avoid_who
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return supplement_evidence_items;
    }

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

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


        

        const updatePayload = {};
        
        if (data.supplement_name !== undefined) updatePayload.supplement_name = data.supplement_name;
        
        
        if (data.evidence_rating !== undefined) updatePayload.evidence_rating = data.evidence_rating;
        
        
        if (data.summary !== undefined) updatePayload.summary = data.summary;
        
        
        if (data.mechanism !== undefined) updatePayload.mechanism = data.mechanism;
        
        
        if (data.benefits !== undefined) updatePayload.benefits = data.benefits;
        
        
        if (data.dosing_range !== undefined) updatePayload.dosing_range = data.dosing_range;
        
        
        if (data.timing_recommendations !== undefined) updatePayload.timing_recommendations = data.timing_recommendations;
        
        
        if (data.interactions !== undefined) updatePayload.interactions = data.interactions;
        
        
        if (data.side_effects !== undefined) updatePayload.side_effects = data.side_effects;
        
        
        if (data.avoid_who !== undefined) updatePayload.avoid_who = data.avoid_who;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        

        
        

        

        return supplement_evidence_items;
    }

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

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

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


        return supplement_evidence_items;
    }

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

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

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

        await supplement_evidence_items.destroy({
            transaction
        });

        return supplement_evidence_items;
    }

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

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

        if (!supplement_evidence_items) {
            return supplement_evidence_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        

        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 = [



    ];

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

            
            if (filter.supplement_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'supplement_evidence_items',
                        'supplement_name',
                        filter.supplement_name,
                    ),
                };
            }
            
            if (filter.summary) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'supplement_evidence_items',
                        'summary',
                        filter.summary,
                    ),
                };
            }
            
            if (filter.mechanism) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'supplement_evidence_items',
                        'mechanism',
                        filter.mechanism,
                    ),
                };
            }
            
            if (filter.benefits) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'supplement_evidence_items',
                        'benefits',
                        filter.benefits,
                    ),
                };
            }
            
            if (filter.dosing_range) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'supplement_evidence_items',
                        'dosing_range',
                        filter.dosing_range,
                    ),
                };
            }
            
            if (filter.timing_recommendations) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'supplement_evidence_items',
                        'timing_recommendations',
                        filter.timing_recommendations,
                    ),
                };
            }
            
            if (filter.interactions) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'supplement_evidence_items',
                        'interactions',
                        filter.interactions,
                    ),
                };
            }
            
            if (filter.side_effects) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'supplement_evidence_items',
                        'side_effects',
                        filter.side_effects,
                    ),
                };
            }
            
            if (filter.avoid_who) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'supplement_evidence_items',
                        'avoid_who',
                        filter.avoid_who,
                    ),
                };
            }
            

            
            

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

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

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

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

            




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

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

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

    
};

