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

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

        const supplements = await db.supplements.create(
            {
                id: data.id || undefined,
        
        supplement_name: data.supplement_name
        ||
        null
            ,
            
        form: data.form
        ||
        null
            ,
            
        dose_amount: data.dose_amount
        ||
        null
            ,
            
        dose_unit: data.dose_unit
        ||
        null
            ,
            
        timing: data.timing
        ||
        null
            ,
            
        with_food: data.with_food
        ||
        null
            ,
            
        brand: data.brand
        ||
        null
            ,
            
        cost_per_dose: data.cost_per_dose
        ||
        null
            ,
            
        reason: data.reason
        ||
        null
            ,
            
        reminders_enabled: data.reminders_enabled
        ||
        false
        
            ,
            
        cycling_enabled: data.cycling_enabled
        ||
        false
        
            ,
            
        cycle_on_days: data.cycle_on_days
        ||
        null
            ,
            
        cycle_off_days: data.cycle_off_days
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await supplements.setUser( data.user || null, {
            transaction,
        });
        

        

        

        return supplements;
    }
    

    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 supplementsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                supplement_name: item.supplement_name
            ||
            null
            ,
            
                form: item.form
            ||
            null
            ,
            
                dose_amount: item.dose_amount
            ||
            null
            ,
            
                dose_unit: item.dose_unit
            ||
            null
            ,
            
                timing: item.timing
            ||
            null
            ,
            
                with_food: item.with_food
            ||
            null
            ,
            
                brand: item.brand
            ||
            null
            ,
            
                cost_per_dose: item.cost_per_dose
            ||
            null
            ,
            
                reason: item.reason
            ||
            null
            ,
            
                reminders_enabled: item.reminders_enabled
            ||
            false
        
            ,
            
                cycling_enabled: item.cycling_enabled
            ||
            false
        
            ,
            
                cycle_on_days: item.cycle_on_days
            ||
            null
            ,
            
                cycle_off_days: item.cycle_off_days
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return supplements;
    }

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

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


        

        const updatePayload = {};
        
        if (data.supplement_name !== undefined) updatePayload.supplement_name = data.supplement_name;
        
        
        if (data.form !== undefined) updatePayload.form = data.form;
        
        
        if (data.dose_amount !== undefined) updatePayload.dose_amount = data.dose_amount;
        
        
        if (data.dose_unit !== undefined) updatePayload.dose_unit = data.dose_unit;
        
        
        if (data.timing !== undefined) updatePayload.timing = data.timing;
        
        
        if (data.with_food !== undefined) updatePayload.with_food = data.with_food;
        
        
        if (data.brand !== undefined) updatePayload.brand = data.brand;
        
        
        if (data.cost_per_dose !== undefined) updatePayload.cost_per_dose = data.cost_per_dose;
        
        
        if (data.reason !== undefined) updatePayload.reason = data.reason;
        
        
        if (data.reminders_enabled !== undefined) updatePayload.reminders_enabled = data.reminders_enabled;
        
        
        if (data.cycling_enabled !== undefined) updatePayload.cycling_enabled = data.cycling_enabled;
        
        
        if (data.cycle_on_days !== undefined) updatePayload.cycle_on_days = data.cycle_on_days;
        
        
        if (data.cycle_off_days !== undefined) updatePayload.cycle_off_days = data.cycle_off_days;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return supplements;
    }

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

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

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


        return supplements;
    }

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

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

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

        await supplements.destroy({
            transaction
        });

        return supplements;
    }

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

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

        if (!supplements) {
            return supplements;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await supplements.getUser({
            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.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}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.supplement_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'supplements',
                        'supplement_name',
                        filter.supplement_name,
                    ),
                };
            }
            
            if (filter.dose_unit) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'supplements',
                        'dose_unit',
                        filter.dose_unit,
                    ),
                };
            }
            
            if (filter.timing) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'supplements',
                        'timing',
                        filter.timing,
                    ),
                };
            }
            
            if (filter.brand) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'supplements',
                        'brand',
                        filter.brand,
                    ),
                };
            }
            
            if (filter.reason) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'supplements',
                        'reason',
                        filter.reason,
                    ),
                };
            }
            

            
            

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    dose_amount: {
                    ...where.dose_amount,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.cost_per_doseRange) {
                const [start, end] = filter.cost_per_doseRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    cost_per_dose: {
                    ...where.cost_per_dose,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.cycle_on_daysRange) {
                const [start, end] = filter.cycle_on_daysRange;

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    cycle_on_days: {
                    ...where.cycle_on_days,
                            [Op.lte]: end,
                    },
                };
                }
            }
            
            if (filter.cycle_off_daysRange) {
                const [start, end] = filter.cycle_off_daysRange;

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

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

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

            
            if (filter.form) {
                where = {
                    ...where,
                form: filter.form,
            };
            }
            
            if (filter.with_food) {
                where = {
                    ...where,
                with_food: filter.with_food,
            };
            }
            
            if (filter.reminders_enabled) {
                where = {
                    ...where,
                reminders_enabled: filter.reminders_enabled,
            };
            }
            
            if (filter.cycling_enabled) {
                where = {
                    ...where,
                cycling_enabled: filter.cycling_enabled,
            };
            }
            


      



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

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

    
};

