
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,
        
        channel: data.channel
        ||
        null
            ,
            
        scheduled_at: data.scheduled_at
        ||
        null
            ,
            
        state: data.state
        ||
        null
            ,
            
        message: data.message
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await reminders.setPatient( data.patient || null, {
            transaction,
        });
        
        await reminders.setEvent( data.event || null, {
            transaction,
        });
        
        await reminders.setRecipient_user( data.recipient_user || null, {
            transaction,
        });
        
        await reminders.setAccounts( data.accounts || 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,
                
                channel: item.channel
            ||
            null
            ,
            
                scheduled_at: item.scheduled_at
            ||
            null
            ,
            
                state: item.state
            ||
            null
            ,
            
                message: item.message
            ||
            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.channel !== undefined) updatePayload.channel = data.channel;
        
        
        if (data.scheduled_at !== undefined) updatePayload.scheduled_at = data.scheduled_at;
        
        
        if (data.state !== undefined) updatePayload.state = data.state;
        
        
        if (data.message !== undefined) updatePayload.message = data.message;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.patient !== undefined) {
            await reminders.setPatient(
              
              data.patient,
              
              { transaction }
            );
        }
        
        if (data.event !== undefined) {
            await reminders.setEvent(
              
              data.event,
              
              { transaction }
            );
        }
        
        if (data.recipient_user !== undefined) {
            await reminders.setRecipient_user(
              
              data.recipient_user,
              
              { transaction }
            );
        }
        
        if (data.accounts !== undefined) {
            await reminders.setAccounts(
              
              data.accounts,
              
              { 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.event = await reminders.getEvent({
            transaction
        });
        
        
        output.recipient_user = await reminders.getRecipient_user({
            transaction
        });
        
        
        output.accounts = await reminders.getAccounts({
            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 userAccounts = (user && user.accounts?.id) || null;
        

        
        if (userAccounts) {
            if (options?.currentUser?.accountsId) {
                where.accountsId = options.currentUser.accountsId;
            }
        }
        

        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)) } },
            {
              last_name: {
                [Op.or]: filter.patient.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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



    ];

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

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

            
            

            
            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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

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


      

      

      

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

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

        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',
                        'channel',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

