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

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

        const medical_appointments = await db.medical_appointments.create(
            {
                id: data.id || undefined,
        
        appointment_start: data.appointment_start
        ||
        null
            ,
            
        appointment_end: data.appointment_end
        ||
        null
            ,
            
        appointment_type: data.appointment_type
        ||
        null
            ,
            
        clinic_location: data.clinic_location
        ||
        null
            ,
            
        notes_to_discuss: data.notes_to_discuss
        ||
        null
            ,
            
        documents_to_bring: data.documents_to_bring
        ||
        null
            ,
            
        post_appointment_notes: data.post_appointment_notes
        ||
        null
            ,
            
        follow_up_instructions: data.follow_up_instructions
        ||
        null
            ,
            
        follow_up_reminder_at: data.follow_up_reminder_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await medical_appointments.setUser( data.user || null, {
            transaction,
        });
        
        await medical_appointments.setProvider( data.provider || null, {
            transaction,
        });
        

        

        

        return medical_appointments;
    }
    

    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 medical_appointmentsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                appointment_start: item.appointment_start
            ||
            null
            ,
            
                appointment_end: item.appointment_end
            ||
            null
            ,
            
                appointment_type: item.appointment_type
            ||
            null
            ,
            
                clinic_location: item.clinic_location
            ||
            null
            ,
            
                notes_to_discuss: item.notes_to_discuss
            ||
            null
            ,
            
                documents_to_bring: item.documents_to_bring
            ||
            null
            ,
            
                post_appointment_notes: item.post_appointment_notes
            ||
            null
            ,
            
                follow_up_instructions: item.follow_up_instructions
            ||
            null
            ,
            
                follow_up_reminder_at: item.follow_up_reminder_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return medical_appointments;
    }

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

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


        

        const updatePayload = {};
        
        if (data.appointment_start !== undefined) updatePayload.appointment_start = data.appointment_start;
        
        
        if (data.appointment_end !== undefined) updatePayload.appointment_end = data.appointment_end;
        
        
        if (data.appointment_type !== undefined) updatePayload.appointment_type = data.appointment_type;
        
        
        if (data.clinic_location !== undefined) updatePayload.clinic_location = data.clinic_location;
        
        
        if (data.notes_to_discuss !== undefined) updatePayload.notes_to_discuss = data.notes_to_discuss;
        
        
        if (data.documents_to_bring !== undefined) updatePayload.documents_to_bring = data.documents_to_bring;
        
        
        if (data.post_appointment_notes !== undefined) updatePayload.post_appointment_notes = data.post_appointment_notes;
        
        
        if (data.follow_up_instructions !== undefined) updatePayload.follow_up_instructions = data.follow_up_instructions;
        
        
        if (data.follow_up_reminder_at !== undefined) updatePayload.follow_up_reminder_at = data.follow_up_reminder_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await medical_appointments.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.provider !== undefined) {
            await medical_appointments.setProvider(
              
              data.provider,
              
              { transaction }
            );
        }
        

        
        

        

        return medical_appointments;
    }

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

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

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


        return medical_appointments;
    }

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

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

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

        await medical_appointments.destroy({
            transaction
        });

        return medical_appointments;
    }

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

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

        if (!medical_appointments) {
            return medical_appointments;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await medical_appointments.getUser({
            transaction
        });
        
        
        output.provider = await medical_appointments.getProvider({
            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.users,
        as: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.clinic_location) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medical_appointments',
                        'clinic_location',
                        filter.clinic_location,
                    ),
                };
            }
            
            if (filter.notes_to_discuss) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medical_appointments',
                        'notes_to_discuss',
                        filter.notes_to_discuss,
                    ),
                };
            }
            
            if (filter.documents_to_bring) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medical_appointments',
                        'documents_to_bring',
                        filter.documents_to_bring,
                    ),
                };
            }
            
            if (filter.post_appointment_notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medical_appointments',
                        'post_appointment_notes',
                        filter.post_appointment_notes,
                    ),
                };
            }
            
            if (filter.follow_up_instructions) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medical_appointments',
                        'follow_up_instructions',
                        filter.follow_up_instructions,
                    ),
                };
            }
            

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

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

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

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

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

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

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

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

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

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


      

      



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

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

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

    
};

