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

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

        const appointments = await db.appointments.create(
            {
                id: data.id || undefined,
        
        scheduled_start_at: data.scheduled_start_at
        ||
        null
            ,
            
        scheduled_end_at: data.scheduled_end_at
        ||
        null
            ,
            
        appointment_type: data.appointment_type
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        reason_for_visit: data.reason_for_visit
        ||
        null
            ,
            
        meeting_link: data.meeting_link
        ||
        null
            ,
            
        meeting_room: data.meeting_room
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await appointments.setPatient( data.patient || null, {
            transaction,
        });
        
        await appointments.setCity_doctor( data.city_doctor || null, {
            transaction,
        });
        
        await appointments.setRural_doctor( data.rural_doctor || null, {
            transaction,
        });
        
        await appointments.setMedical_camp( data.medical_camp || null, {
            transaction,
        });
        

        

        

        return 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 appointmentsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                scheduled_start_at: item.scheduled_start_at
            ||
            null
            ,
            
                scheduled_end_at: item.scheduled_end_at
            ||
            null
            ,
            
                appointment_type: item.appointment_type
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                reason_for_visit: item.reason_for_visit
            ||
            null
            ,
            
                meeting_link: item.meeting_link
            ||
            null
            ,
            
                meeting_room: item.meeting_room
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return appointments;
    }

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

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


        

        const updatePayload = {};
        
        if (data.scheduled_start_at !== undefined) updatePayload.scheduled_start_at = data.scheduled_start_at;
        
        
        if (data.scheduled_end_at !== undefined) updatePayload.scheduled_end_at = data.scheduled_end_at;
        
        
        if (data.appointment_type !== undefined) updatePayload.appointment_type = data.appointment_type;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.reason_for_visit !== undefined) updatePayload.reason_for_visit = data.reason_for_visit;
        
        
        if (data.meeting_link !== undefined) updatePayload.meeting_link = data.meeting_link;
        
        
        if (data.meeting_room !== undefined) updatePayload.meeting_room = data.meeting_room;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.patient !== undefined) {
            await appointments.setPatient(
              
              data.patient,
              
              { transaction }
            );
        }
        
        if (data.city_doctor !== undefined) {
            await appointments.setCity_doctor(
              
              data.city_doctor,
              
              { transaction }
            );
        }
        
        if (data.rural_doctor !== undefined) {
            await appointments.setRural_doctor(
              
              data.rural_doctor,
              
              { transaction }
            );
        }
        
        if (data.medical_camp !== undefined) {
            await appointments.setMedical_camp(
              
              data.medical_camp,
              
              { transaction }
            );
        }
        

        
        

        

        return appointments;
    }

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

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

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


        return appointments;
    }

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

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

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

        await appointments.destroy({
            transaction
        });

        return appointments;
    }

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

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

        if (!appointments) {
            return appointments;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.patient = await appointments.getPatient({
            transaction
        });
        
        
        output.city_doctor = await appointments.getCity_doctor({
            transaction
        });
        
        
        output.rural_doctor = await appointments.getRural_doctor({
            transaction
        });
        
        
        output.medical_camp = await appointments.getMedical_camp({
            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}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

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



    ];

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

            
            if (filter.reason_for_visit) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'appointments',
                        'reason_for_visit',
                        filter.reason_for_visit,
                    ),
                };
            }
            
            if (filter.meeting_link) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'appointments',
                        'meeting_link',
                        filter.meeting_link,
                    ),
                };
            }
            
            if (filter.meeting_room) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'appointments',
                        'meeting_room',
                        filter.meeting_room,
                    ),
                };
            }
            

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    scheduled_end_at: {
                    ...where.scheduled_end_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.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.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(
                        'appointments',
                        'reason_for_visit',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

