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

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

        const patients = await db.patients.create(
            {
                id: data.id || undefined,
        
        full_name: data.full_name
        ||
        null
            ,
            
        national_number: data.national_number
        ||
        null
            ,
            
        phone: data.phone
        ||
        null
            ,
            
        address: data.address
        ||
        null
            ,
            
        blood_group: data.blood_group
        ||
        null
            ,
            
        gender: data.gender
        ||
        null
            ,
            
        birth_date: data.birth_date
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await patients.setPrimary_doctor( data.primary_doctor || null, {
            transaction,
        });
        

        

        

        return patients;
    }
    

    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 patientsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                full_name: item.full_name
            ||
            null
            ,
            
                national_number: item.national_number
            ||
            null
            ,
            
                phone: item.phone
            ||
            null
            ,
            
                address: item.address
            ||
            null
            ,
            
                blood_group: item.blood_group
            ||
            null
            ,
            
                gender: item.gender
            ||
            null
            ,
            
                birth_date: item.birth_date
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return patients;
    }

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

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


        

        const updatePayload = {};
        
        if (data.full_name !== undefined) updatePayload.full_name = data.full_name;
        
        
        if (data.national_number !== undefined) updatePayload.national_number = data.national_number;
        
        
        if (data.phone !== undefined) updatePayload.phone = data.phone;
        
        
        if (data.address !== undefined) updatePayload.address = data.address;
        
        
        if (data.blood_group !== undefined) updatePayload.blood_group = data.blood_group;
        
        
        if (data.gender !== undefined) updatePayload.gender = data.gender;
        
        
        if (data.birth_date !== undefined) updatePayload.birth_date = data.birth_date;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.primary_doctor !== undefined) {
            await patients.setPrimary_doctor(
              
              data.primary_doctor,
              
              { transaction }
            );
        }
        

        
        

        

        return patients;
    }

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

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

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


        return patients;
    }

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

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

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

        await patients.destroy({
            transaction
        });

        return patients;
    }

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

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

        if (!patients) {
            return patients;
        }

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

        
        
        
        
        
        output.guarantors_patient = await patients.getGuarantors_patient({
            transaction
        });
        
        
        
        output.visits_patient = await patients.getVisits_patient({
            transaction
        });
        
        
        output.orders_patient = await patients.getOrders_patient({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.surgery_cases_patient = await patients.getSurgery_cases_patient({
            transaction
        });
        
        
        
        
        output.cathlab_cases_patient = await patients.getCathlab_cases_patient({
            transaction
        });
        
        
        output.ecg_stress_tests_patient = await patients.getEcg_stress_tests_patient({
            transaction
        });
        
        
        
        
        
        
        output.pharmacy_sales_invoices_patient = await patients.getPharmacy_sales_invoices_patient({
            transaction
        });
        
        
        
        
        output.patient_invoices_patient = await patients.getPatient_invoices_patient({
            transaction
        });
        
        
        
        
        
        
        
        output.room_bookings_patient = await patients.getRoom_bookings_patient({
            transaction
        });
        
        
        
        
        output.maternity_cases_patient = await patients.getMaternity_cases_patient({
            transaction
        });
        
        
        output.pregnancy_followups_patient = await patients.getPregnancy_followups_patient({
            transaction
        });
        
        
        
        output.daily_followup_clinic_patient = await patients.getDaily_followup_clinic_patient({
            transaction
        });
        
        
        
        
        
        output.primary_doctor = await patients.getPrimary_doctor({
            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.doctors,
        as: 'primary_doctor',
        
        where: filter.primary_doctor ? {
          [Op.or]: [
            { id: { [Op.in]: filter.primary_doctor.split('|').map(term => Utils.uuid(term)) } },
            {
              full_name: {
                [Op.or]: filter.primary_doctor.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

            
            if (filter.full_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'patients',
                        'full_name',
                        filter.full_name,
                    ),
                };
            }
            
            if (filter.national_number) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'patients',
                        'national_number',
                        filter.national_number,
                    ),
                };
            }
            
            if (filter.phone) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'patients',
                        'phone',
                        filter.phone,
                    ),
                };
            }
            
            if (filter.address) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'patients',
                        'address',
                        filter.address,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      



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

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

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

    
};

