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

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

        const medicine_reminders = await db.medicine_reminders.create(
            {
                id: data.id || undefined,
        
        medicine_label: data.medicine_label
        ||
        null
            ,
            
        dosage: data.dosage
        ||
        null
            ,
            
        frequency: data.frequency
        ||
        null
            ,
            
        start_at: data.start_at
        ||
        null
            ,
            
        end_at: data.end_at
        ||
        null
            ,
            
        next_due_at: data.next_due_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        instructions: data.instructions
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await medicine_reminders.setPatient( data.patient || null, {
            transaction,
        });
        
        await medicine_reminders.setMedical_report( data.medical_report || null, {
            transaction,
        });
        

        

        

        return medicine_reminders;
    }
    

    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 medicine_remindersData = data.map((item, index) => ({
                id: item.id || undefined,
                
                medicine_label: item.medicine_label
            ||
            null
            ,
            
                dosage: item.dosage
            ||
            null
            ,
            
                frequency: item.frequency
            ||
            null
            ,
            
                start_at: item.start_at
            ||
            null
            ,
            
                end_at: item.end_at
            ||
            null
            ,
            
                next_due_at: item.next_due_at
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                instructions: item.instructions
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return medicine_reminders;
    }

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

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


        

        const updatePayload = {};
        
        if (data.medicine_label !== undefined) updatePayload.medicine_label = data.medicine_label;
        
        
        if (data.dosage !== undefined) updatePayload.dosage = data.dosage;
        
        
        if (data.frequency !== undefined) updatePayload.frequency = data.frequency;
        
        
        if (data.start_at !== undefined) updatePayload.start_at = data.start_at;
        
        
        if (data.end_at !== undefined) updatePayload.end_at = data.end_at;
        
        
        if (data.next_due_at !== undefined) updatePayload.next_due_at = data.next_due_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.instructions !== undefined) updatePayload.instructions = data.instructions;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.patient !== undefined) {
            await medicine_reminders.setPatient(
              
              data.patient,
              
              { transaction }
            );
        }
        
        if (data.medical_report !== undefined) {
            await medicine_reminders.setMedical_report(
              
              data.medical_report,
              
              { transaction }
            );
        }
        

        
        

        

        return medicine_reminders;
    }

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

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

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


        return medicine_reminders;
    }

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

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

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

        await medicine_reminders.destroy({
            transaction
        });

        return medicine_reminders;
    }

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

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

        if (!medicine_reminders) {
            return medicine_reminders;
        }

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

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

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



    ];

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

            
            if (filter.medicine_label) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medicine_reminders',
                        'medicine_label',
                        filter.medicine_label,
                    ),
                };
            }
            
            if (filter.dosage) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medicine_reminders',
                        'dosage',
                        filter.dosage,
                    ),
                };
            }
            
            if (filter.instructions) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medicine_reminders',
                        'instructions',
                        filter.instructions,
                    ),
                };
            }
            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            start_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    end_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

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

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

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

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

            
            if (filter.frequency) {
                where = {
                    ...where,
                frequency: filter.frequency,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            


      

      



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

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

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

    
};

