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

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

        const vaccination_reminders = await db.vaccination_reminders.create(
            {
                id: data.id || undefined,
        
        vaccine_name: data.vaccine_name
        ||
        null
            ,
            
        dose_number: data.dose_number
        ||
        null
            ,
            
        due_at: data.due_at
        ||
        null
            ,
            
        sent_at: data.sent_at
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await vaccination_reminders.setPatient( data.patient || null, {
            transaction,
        });
        

        

        

        return vaccination_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 vaccination_remindersData = data.map((item, index) => ({
                id: item.id || undefined,
                
                vaccine_name: item.vaccine_name
            ||
            null
            ,
            
                dose_number: item.dose_number
            ||
            null
            ,
            
                due_at: item.due_at
            ||
            null
            ,
            
                sent_at: item.sent_at
            ||
            null
            ,
            
                status: item.status
            ||
            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 vaccination_reminders = await db.vaccination_reminders.bulkCreate(vaccination_remindersData, { transaction });

        // For each item created, replace relation files
        

        return vaccination_reminders;
    }

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

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


        

        const updatePayload = {};
        
        if (data.vaccine_name !== undefined) updatePayload.vaccine_name = data.vaccine_name;
        
        
        if (data.dose_number !== undefined) updatePayload.dose_number = data.dose_number;
        
        
        if (data.due_at !== undefined) updatePayload.due_at = data.due_at;
        
        
        if (data.sent_at !== undefined) updatePayload.sent_at = data.sent_at;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return vaccination_reminders;
    }

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

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

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


        return vaccination_reminders;
    }

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

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

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

        await vaccination_reminders.destroy({
            transaction
        });

        return vaccination_reminders;
    }

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

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

        if (!vaccination_reminders) {
            return vaccination_reminders;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.patient = await vaccination_reminders.getPatient({
            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}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.vaccine_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vaccination_reminders',
                        'vaccine_name',
                        filter.vaccine_name,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'vaccination_reminders',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    due_at: {
                    ...where.due_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.dose_number) {
                where = {
                    ...where,
                dose_number: filter.dose_number,
            };
            }
            
            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.vaccination_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(
                        'vaccination_reminders',
                        'vaccine_name',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

