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

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

        const prescriptions = await db.prescriptions.create(
            {
                id: data.id || undefined,
        
        prescribed_at: data.prescribed_at
        ||
        null
            ,
            
        prescription_status: data.prescription_status
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await prescriptions.setPatient( data.patient || null, {
            transaction,
        });
        
        await prescriptions.setConsultation( data.consultation || null, {
            transaction,
        });
        
        await prescriptions.setPrescribed_by_doctor( data.prescribed_by_doctor || null, {
            transaction,
        });
        
        await prescriptions.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.prescriptions.getTableName(),
                belongsToColumn: 'prescription_files',
                belongsToId: prescriptions.id,
            },
            data.prescription_files,
            options,
        );
        

        return prescriptions;
    }
    

    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 prescriptionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                prescribed_at: item.prescribed_at
            ||
            null
            ,
            
                prescription_status: item.prescription_status
            ||
            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 prescriptions = await db.prescriptions.bulkCreate(prescriptionsData, { transaction });

        // For each item created, replace relation files
        
        for (let i = 0; i < prescriptions.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.prescriptions.getTableName(),
                    belongsToColumn: 'prescription_files',
                    belongsToId: prescriptions[i].id,
                },
                data[i].prescription_files,
                options,
            );
        }
        

        return prescriptions;
    }

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


        

        const updatePayload = {};
        
        if (data.prescribed_at !== undefined) updatePayload.prescribed_at = data.prescribed_at;
        
        
        if (data.prescription_status !== undefined) updatePayload.prescription_status = data.prescription_status;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.patient !== undefined) {
            await prescriptions.setPatient(
              
              data.patient,
              
              { transaction }
            );
        }
        
        if (data.consultation !== undefined) {
            await prescriptions.setConsultation(
              
              data.consultation,
              
              { transaction }
            );
        }
        
        if (data.prescribed_by_doctor !== undefined) {
            await prescriptions.setPrescribed_by_doctor(
              
              data.prescribed_by_doctor,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await prescriptions.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.prescriptions.getTableName(),
                belongsToColumn: 'prescription_files',
                belongsToId: prescriptions.id,
            },
            data.prescription_files,
            options,
        );
        

        return prescriptions;
    }

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

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

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


        return prescriptions;
    }

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

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

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

        await prescriptions.destroy({
            transaction
        });

        return prescriptions;
    }

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

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

        if (!prescriptions) {
            return prescriptions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.prescription_items_prescription = await prescriptions.getPrescription_items_prescription({
            transaction
        });
        
        
        output.medicine_dispatches_prescription = await prescriptions.getMedicine_dispatches_prescription({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        output.patient = await prescriptions.getPatient({
            transaction
        });
        
        
        output.consultation = await prescriptions.getConsultation({
            transaction
        });
        
        
        output.prescribed_by_doctor = await prescriptions.getPrescribed_by_doctor({
            transaction
        });
        
        
        output.prescription_files = await prescriptions.getPrescription_files({
            transaction
        });
        
        
        output.organizations = await prescriptions.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.consultations,
        as: 'consultation',
        
        where: filter.consultation ? {
          [Op.or]: [
            { id: { [Op.in]: filter.consultation.split('|').map(term => Utils.uuid(term)) } },
            {
              chief_complaint: {
                [Op.or]: filter.consultation.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

      {
        model: db.organizations,
        as: 'organizations',
        
      },



      {
        model: db.file,
        as: 'prescription_files',
      },

    ];

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

            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'prescriptions',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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

        const records = await db.prescriptions.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,
        }));
    }

    
};

