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

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

        const patient_vaccinations = await db.patient_vaccinations.create(
            {
                id: data.id || undefined,
        
        due_at: data.due_at
        ||
        null
            ,
            
        administered_at: data.administered_at
        ||
        null
            ,
            
        vaccination_status: data.vaccination_status
        ||
        null
            ,
            
        administered_by: data.administered_by
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await patient_vaccinations.setPatient( data.patient || null, {
            transaction,
        });
        
        await patient_vaccinations.setVaccination( data.vaccination || null, {
            transaction,
        });
        
        await patient_vaccinations.setAdministered_at_camp( data.administered_at_camp || null, {
            transaction,
        });
        
        await patient_vaccinations.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return patient_vaccinations;
    }
    

    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 patient_vaccinationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                due_at: item.due_at
            ||
            null
            ,
            
                administered_at: item.administered_at
            ||
            null
            ,
            
                vaccination_status: item.vaccination_status
            ||
            null
            ,
            
                administered_by: item.administered_by
            ||
            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 patient_vaccinations = await db.patient_vaccinations.bulkCreate(patient_vaccinationsData, { transaction });

        // For each item created, replace relation files
        

        return patient_vaccinations;
    }

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


        

        const updatePayload = {};
        
        if (data.due_at !== undefined) updatePayload.due_at = data.due_at;
        
        
        if (data.administered_at !== undefined) updatePayload.administered_at = data.administered_at;
        
        
        if (data.vaccination_status !== undefined) updatePayload.vaccination_status = data.vaccination_status;
        
        
        if (data.administered_by !== undefined) updatePayload.administered_by = data.administered_by;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.patient !== undefined) {
            await patient_vaccinations.setPatient(
              
              data.patient,
              
              { transaction }
            );
        }
        
        if (data.vaccination !== undefined) {
            await patient_vaccinations.setVaccination(
              
              data.vaccination,
              
              { transaction }
            );
        }
        
        if (data.administered_at_camp !== undefined) {
            await patient_vaccinations.setAdministered_at_camp(
              
              data.administered_at_camp,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await patient_vaccinations.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return patient_vaccinations;
    }

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

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

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


        return patient_vaccinations;
    }

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

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

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

        await patient_vaccinations.destroy({
            transaction
        });

        return patient_vaccinations;
    }

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

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

        if (!patient_vaccinations) {
            return patient_vaccinations;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.reminders_patient_vaccination = await patient_vaccinations.getReminders_patient_vaccination({
            transaction
        });
        
        
        
        
        
        
        
        
        output.patient = await patient_vaccinations.getPatient({
            transaction
        });
        
        
        output.vaccination = await patient_vaccinations.getVaccination({
            transaction
        });
        
        
        output.administered_at_camp = await patient_vaccinations.getAdministered_at_camp({
            transaction
        });
        
        
        output.organizations = await patient_vaccinations.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.vaccinations,
        as: 'vaccination',
        
        where: filter.vaccination ? {
          [Op.or]: [
            { id: { [Op.in]: filter.vaccination.split('|').map(term => Utils.uuid(term)) } },
            {
              vaccine_name: {
                [Op.or]: filter.vaccination.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.medical_camps,
        as: 'administered_at_camp',
        
        where: filter.administered_at_camp ? {
          [Op.or]: [
            { id: { [Op.in]: filter.administered_at_camp.split('|').map(term => Utils.uuid(term)) } },
            {
              camp_name: {
                [Op.or]: filter.administered_at_camp.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.administered_by) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'patient_vaccinations',
                        'administered_by',
                        filter.administered_by,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'patient_vaccinations',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            due_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    administered_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.administered_atRange) {
                const [start, end] = filter.administered_atRange;

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

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

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

            
            if (filter.vaccination_status) {
                where = {
                    ...where,
                vaccination_status: filter.vaccination_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.patient_vaccinations.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(
                        'patient_vaccinations',
                        'notes',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

