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

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

        const medications = await db.medications.create(
            {
                id: data.id || undefined,
        
        medication_name: data.medication_name
        ||
        null
            ,
            
        dose_amount: data.dose_amount
        ||
        null
            ,
            
        dose_unit: data.dose_unit
        ||
        null
            ,
            
        frequency_type: data.frequency_type
        ||
        null
            ,
            
        frequency_interval_hours: data.frequency_interval_hours
        ||
        null
            ,
            
        frequency_notes: data.frequency_notes
        ||
        null
            ,
            
        route: data.route
        ||
        null
            ,
            
        condition_treated: data.condition_treated
        ||
        null
            ,
            
        start_date: data.start_date
        ||
        null
            ,
            
        end_date: data.end_date
        ||
        null
            ,
            
        refill_reminder_date: data.refill_reminder_date
        ||
        null
            ,
            
        reminders_enabled: data.reminders_enabled
        ||
        false
        
            ,
            
        is_controlled_substance: data.is_controlled_substance
        ||
        false
        
            ,
            
        instructions: data.instructions
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await medications.setUser( data.user || null, {
            transaction,
        });
        
        await medications.setPrescribing_provider( data.prescribing_provider || null, {
            transaction,
        });
        
        await medications.setPharmacy( data.pharmacy || null, {
            transaction,
        });
        

        

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

        return medications;
    }
    

    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 medicationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                medication_name: item.medication_name
            ||
            null
            ,
            
                dose_amount: item.dose_amount
            ||
            null
            ,
            
                dose_unit: item.dose_unit
            ||
            null
            ,
            
                frequency_type: item.frequency_type
            ||
            null
            ,
            
                frequency_interval_hours: item.frequency_interval_hours
            ||
            null
            ,
            
                frequency_notes: item.frequency_notes
            ||
            null
            ,
            
                route: item.route
            ||
            null
            ,
            
                condition_treated: item.condition_treated
            ||
            null
            ,
            
                start_date: item.start_date
            ||
            null
            ,
            
                end_date: item.end_date
            ||
            null
            ,
            
                refill_reminder_date: item.refill_reminder_date
            ||
            null
            ,
            
                reminders_enabled: item.reminders_enabled
            ||
            false
        
            ,
            
                is_controlled_substance: item.is_controlled_substance
            ||
            false
        
            ,
            
                instructions: item.instructions
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return medications;
    }

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

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


        

        const updatePayload = {};
        
        if (data.medication_name !== undefined) updatePayload.medication_name = data.medication_name;
        
        
        if (data.dose_amount !== undefined) updatePayload.dose_amount = data.dose_amount;
        
        
        if (data.dose_unit !== undefined) updatePayload.dose_unit = data.dose_unit;
        
        
        if (data.frequency_type !== undefined) updatePayload.frequency_type = data.frequency_type;
        
        
        if (data.frequency_interval_hours !== undefined) updatePayload.frequency_interval_hours = data.frequency_interval_hours;
        
        
        if (data.frequency_notes !== undefined) updatePayload.frequency_notes = data.frequency_notes;
        
        
        if (data.route !== undefined) updatePayload.route = data.route;
        
        
        if (data.condition_treated !== undefined) updatePayload.condition_treated = data.condition_treated;
        
        
        if (data.start_date !== undefined) updatePayload.start_date = data.start_date;
        
        
        if (data.end_date !== undefined) updatePayload.end_date = data.end_date;
        
        
        if (data.refill_reminder_date !== undefined) updatePayload.refill_reminder_date = data.refill_reminder_date;
        
        
        if (data.reminders_enabled !== undefined) updatePayload.reminders_enabled = data.reminders_enabled;
        
        
        if (data.is_controlled_substance !== undefined) updatePayload.is_controlled_substance = data.is_controlled_substance;
        
        
        if (data.instructions !== undefined) updatePayload.instructions = data.instructions;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await medications.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.prescribing_provider !== undefined) {
            await medications.setPrescribing_provider(
              
              data.prescribing_provider,
              
              { transaction }
            );
        }
        
        if (data.pharmacy !== undefined) {
            await medications.setPharmacy(
              
              data.pharmacy,
              
              { transaction }
            );
        }
        

        
        

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

        return medications;
    }

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

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

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


        return medications;
    }

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

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

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

        await medications.destroy({
            transaction
        });

        return medications;
    }

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

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

        if (!medications) {
            return medications;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.medication_doses_medication = await medications.getMedication_doses_medication({
            transaction
        });
        
        
        output.medication_side_effects_medication = await medications.getMedication_side_effects_medication({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await medications.getUser({
            transaction
        });
        
        
        output.prescribing_provider = await medications.getPrescribing_provider({
            transaction
        });
        
        
        output.pharmacy = await medications.getPharmacy({
            transaction
        });
        
        
        output.medication_photos = await medications.getMedication_photos({
            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}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



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

    ];

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

            
            if (filter.medication_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medications',
                        'medication_name',
                        filter.medication_name,
                    ),
                };
            }
            
            if (filter.frequency_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medications',
                        'frequency_notes',
                        filter.frequency_notes,
                    ),
                };
            }
            
            if (filter.condition_treated) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medications',
                        'condition_treated',
                        filter.condition_treated,
                    ),
                };
            }
            
            if (filter.instructions) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medications',
                        'instructions',
                        filter.instructions,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medications',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

            
            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.frequency_interval_hoursRange) {
                const [start, end] = filter.frequency_interval_hoursRange;

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

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

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

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

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

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

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

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

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

            
            if (filter.dose_unit) {
                where = {
                    ...where,
                dose_unit: filter.dose_unit,
            };
            }
            
            if (filter.frequency_type) {
                where = {
                    ...where,
                frequency_type: filter.frequency_type,
            };
            }
            
            if (filter.route) {
                where = {
                    ...where,
                route: filter.route,
            };
            }
            
            if (filter.reminders_enabled) {
                where = {
                    ...where,
                reminders_enabled: filter.reminders_enabled,
            };
            }
            
            if (filter.is_controlled_substance) {
                where = {
                    ...where,
                is_controlled_substance: filter.is_controlled_substance,
            };
            }
            


      

      

      



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

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

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

    
};

