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

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

        const visits = await db.visits.create(
            {
                id: data.id || undefined,
        
        visit_number: data.visit_number
        ||
        null
            ,
            
        department: data.department
        ||
        null
            ,
            
        visit_price: data.visit_price
        ||
        null
            ,
            
        arrival_time: data.arrival_time
        ||
        null
            ,
            
        discharge_time: data.discharge_time
        ||
        null
            ,
            
        blood_pressure: data.blood_pressure
        ||
        null
            ,
            
        glucose: data.glucose
        ||
        null
            ,
            
        pulse: data.pulse
        ||
        null
            ,
            
        temperature: data.temperature
        ||
        null
            ,
            
        spo2: data.spo2
        ||
        null
            ,
            
        chief_complaint: data.chief_complaint
        ||
        null
            ,
            
        initial_diagnosis: data.initial_diagnosis
        ||
        null
            ,
            
        emergency_treatment: data.emergency_treatment
        ||
        null
            ,
            
        fluids_iv: data.fluids_iv
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await visits.setPatient( data.patient || null, {
            transaction,
        });
        
        await visits.setGuarantor( data.guarantor || null, {
            transaction,
        });
        
        await visits.setDoctor( data.doctor || null, {
            transaction,
        });
        

        

        

        return visits;
    }
    

    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 visitsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                visit_number: item.visit_number
            ||
            null
            ,
            
                department: item.department
            ||
            null
            ,
            
                visit_price: item.visit_price
            ||
            null
            ,
            
                arrival_time: item.arrival_time
            ||
            null
            ,
            
                discharge_time: item.discharge_time
            ||
            null
            ,
            
                blood_pressure: item.blood_pressure
            ||
            null
            ,
            
                glucose: item.glucose
            ||
            null
            ,
            
                pulse: item.pulse
            ||
            null
            ,
            
                temperature: item.temperature
            ||
            null
            ,
            
                spo2: item.spo2
            ||
            null
            ,
            
                chief_complaint: item.chief_complaint
            ||
            null
            ,
            
                initial_diagnosis: item.initial_diagnosis
            ||
            null
            ,
            
                emergency_treatment: item.emergency_treatment
            ||
            null
            ,
            
                fluids_iv: item.fluids_iv
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return visits;
    }

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

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


        

        const updatePayload = {};
        
        if (data.visit_number !== undefined) updatePayload.visit_number = data.visit_number;
        
        
        if (data.department !== undefined) updatePayload.department = data.department;
        
        
        if (data.visit_price !== undefined) updatePayload.visit_price = data.visit_price;
        
        
        if (data.arrival_time !== undefined) updatePayload.arrival_time = data.arrival_time;
        
        
        if (data.discharge_time !== undefined) updatePayload.discharge_time = data.discharge_time;
        
        
        if (data.blood_pressure !== undefined) updatePayload.blood_pressure = data.blood_pressure;
        
        
        if (data.glucose !== undefined) updatePayload.glucose = data.glucose;
        
        
        if (data.pulse !== undefined) updatePayload.pulse = data.pulse;
        
        
        if (data.temperature !== undefined) updatePayload.temperature = data.temperature;
        
        
        if (data.spo2 !== undefined) updatePayload.spo2 = data.spo2;
        
        
        if (data.chief_complaint !== undefined) updatePayload.chief_complaint = data.chief_complaint;
        
        
        if (data.initial_diagnosis !== undefined) updatePayload.initial_diagnosis = data.initial_diagnosis;
        
        
        if (data.emergency_treatment !== undefined) updatePayload.emergency_treatment = data.emergency_treatment;
        
        
        if (data.fluids_iv !== undefined) updatePayload.fluids_iv = data.fluids_iv;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.patient !== undefined) {
            await visits.setPatient(
              
              data.patient,
              
              { transaction }
            );
        }
        
        if (data.guarantor !== undefined) {
            await visits.setGuarantor(
              
              data.guarantor,
              
              { transaction }
            );
        }
        
        if (data.doctor !== undefined) {
            await visits.setDoctor(
              
              data.doctor,
              
              { transaction }
            );
        }
        

        
        

        

        return visits;
    }

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

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

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


        return visits;
    }

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

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

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

        await visits.destroy({
            transaction
        });

        return visits;
    }

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

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

        if (!visits) {
            return visits;
        }

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

        
        
        
        
        
        
        
        
        output.orders_visit = await visits.getOrders_visit({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.endoscopy_cases_visit = await visits.getEndoscopy_cases_visit({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.patient = await visits.getPatient({
            transaction
        });
        
        
        output.guarantor = await visits.getGuarantor({
            transaction
        });
        
        
        output.doctor = await visits.getDoctor({
            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.guarantors,
        as: 'guarantor',
        
        where: filter.guarantor ? {
          [Op.or]: [
            { id: { [Op.in]: filter.guarantor.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.guarantor.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.visit_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'visits',
                        'visit_number',
                        filter.visit_number,
                    ),
                };
            }
            
            if (filter.blood_pressure) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'visits',
                        'blood_pressure',
                        filter.blood_pressure,
                    ),
                };
            }
            
            if (filter.chief_complaint) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'visits',
                        'chief_complaint',
                        filter.chief_complaint,
                    ),
                };
            }
            
            if (filter.initial_diagnosis) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'visits',
                        'initial_diagnosis',
                        filter.initial_diagnosis,
                    ),
                };
            }
            
            if (filter.emergency_treatment) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'visits',
                        'emergency_treatment',
                        filter.emergency_treatment,
                    ),
                };
            }
            
            if (filter.fluids_iv) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'visits',
                        'fluids_iv',
                        filter.fluids_iv,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'visits',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            
            if (filter.department) {
                where = {
                    ...where,
                department: filter.department,
            };
            }
            
            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.visits.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(
                        'visits',
                        'visit_number',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

