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

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

        const reminders = await db.reminders.create(
            {
                id: data.id || undefined,
        
        reminder_type: data.reminder_type
        ||
        null
            ,
            
        scheduled_at: data.scheduled_at
        ||
        null
            ,
            
        sent_at: data.sent_at
        ||
        null
            ,
            
        channel: data.channel
        ||
        null
            ,
            
        delivery_status: data.delivery_status
        ||
        null
            ,
            
        message_text: data.message_text
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await reminders.setPatient( data.patient || null, {
            transaction,
        });
        
        await reminders.setPrescription_item( data.prescription_item || null, {
            transaction,
        });
        
        await reminders.setPatient_vaccination( data.patient_vaccination || null, {
            transaction,
        });
        
        await reminders.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return 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 remindersData = data.map((item, index) => ({
                id: item.id || undefined,
                
                reminder_type: item.reminder_type
            ||
            null
            ,
            
                scheduled_at: item.scheduled_at
            ||
            null
            ,
            
                sent_at: item.sent_at
            ||
            null
            ,
            
                channel: item.channel
            ||
            null
            ,
            
                delivery_status: item.delivery_status
            ||
            null
            ,
            
                message_text: item.message_text
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return reminders;
    }

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


        

        const updatePayload = {};
        
        if (data.reminder_type !== undefined) updatePayload.reminder_type = data.reminder_type;
        
        
        if (data.scheduled_at !== undefined) updatePayload.scheduled_at = data.scheduled_at;
        
        
        if (data.sent_at !== undefined) updatePayload.sent_at = data.sent_at;
        
        
        if (data.channel !== undefined) updatePayload.channel = data.channel;
        
        
        if (data.delivery_status !== undefined) updatePayload.delivery_status = data.delivery_status;
        
        
        if (data.message_text !== undefined) updatePayload.message_text = data.message_text;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.patient !== undefined) {
            await reminders.setPatient(
              
              data.patient,
              
              { transaction }
            );
        }
        
        if (data.prescription_item !== undefined) {
            await reminders.setPrescription_item(
              
              data.prescription_item,
              
              { transaction }
            );
        }
        
        if (data.patient_vaccination !== undefined) {
            await reminders.setPatient_vaccination(
              
              data.patient_vaccination,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await reminders.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return reminders;
    }

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

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

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


        return reminders;
    }

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

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

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

        await reminders.destroy({
            transaction
        });

        return reminders;
    }

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

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

        if (!reminders) {
            return reminders;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.patient = await reminders.getPatient({
            transaction
        });
        
        
        output.prescription_item = await reminders.getPrescription_item({
            transaction
        });
        
        
        output.patient_vaccination = await reminders.getPatient_vaccination({
            transaction
        });
        
        
        output.organizations = await reminders.getOrganizations({
            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 userOrganizations = (user && user.organizations?.id) || null;
        

        
        if (userOrganizations) {
            if (options?.currentUser?.organizationsId) {
                where.organizationsId = options.currentUser.organizationsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

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

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

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



    ];

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

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

            
            

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

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

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

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

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

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

            
            if (filter.reminder_type) {
                where = {
                    ...where,
                reminder_type: filter.reminder_type,
            };
            }
            
            if (filter.channel) {
                where = {
                    ...where,
                channel: filter.channel,
            };
            }
            
            if (filter.delivery_status) {
                where = {
                    ...where,
                delivery_status: filter.delivery_status,
            };
            }
            


      

      

      

      
      if (filter.organizations) {
        const listItems = filter.organizations.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          organizationsId: {[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.organizationsId;
        }
        

        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.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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'reminders',
                        'message_text',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

