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

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

        const medications = await db.medications.create(
            {
                id: data.id || undefined,
        
        medication_name: data.medication_name
        ||
        null
            ,
            
        dosage: data.dosage
        ||
        null
            ,
            
        route: data.route
        ||
        null
            ,
            
        instructions: data.instructions
        ||
        null
            ,
            
        start_at: data.start_at
        ||
        null
            ,
            
        end_at: data.end_at
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await medications.setPatient( data.patient || null, {
            transaction,
        });
        
        await medications.setPrescribed_by( data.prescribed_by || null, {
            transaction,
        });
        
        await medications.setAccounts( data.accounts || null, {
            transaction,
        });
        

        

        

        return medications;
    }
    

    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 medicationsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                medication_name: item.medication_name
            ||
            null
            ,
            
                dosage: item.dosage
            ||
            null
            ,
            
                route: item.route
            ||
            null
            ,
            
                instructions: item.instructions
            ||
            null
            ,
            
                start_at: item.start_at
            ||
            null
            ,
            
                end_at: item.end_at
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return medications;
    }

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


        

        const updatePayload = {};
        
        if (data.medication_name !== undefined) updatePayload.medication_name = data.medication_name;
        
        
        if (data.dosage !== undefined) updatePayload.dosage = data.dosage;
        
        
        if (data.route !== undefined) updatePayload.route = data.route;
        
        
        if (data.instructions !== undefined) updatePayload.instructions = data.instructions;
        
        
        if (data.start_at !== undefined) updatePayload.start_at = data.start_at;
        
        
        if (data.end_at !== undefined) updatePayload.end_at = data.end_at;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.patient !== undefined) {
            await medications.setPatient(
              
              data.patient,
              
              { transaction }
            );
        }
        
        if (data.prescribed_by !== undefined) {
            await medications.setPrescribed_by(
              
              data.prescribed_by,
              
              { transaction }
            );
        }
        
        if (data.accounts !== undefined) {
            await medications.setAccounts(
              
              data.accounts,
              
              { transaction }
            );
        }
        

        
        

        

        return medications;
    }

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

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

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


        return medications;
    }

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

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

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

        await medications.destroy({
            transaction
        });

        return medications;
    }

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

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

        if (!medications) {
            return medications;
        }

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

        
        
        
        
        
        
        
        
        output.medication_schedules_medication = await medications.getMedication_schedules_medication({
            transaction
        });
        
        
        output.calendar_events_linked_medication = await medications.getCalendar_events_linked_medication({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.patient = await medications.getPatient({
            transaction
        });
        
        
        output.prescribed_by = await medications.getPrescribed_by({
            transaction
        });
        
        
        output.accounts = await medications.getAccounts({
            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 userAccounts = (user && user.accounts?.id) || null;
        

        
        if (userAccounts) {
            if (options?.currentUser?.accountsId) {
                where.accountsId = options.currentUser.accountsId;
            }
        }
        

        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)) } },
            {
              last_name: {
                [Op.or]: filter.patient.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            
            if (filter.medication_name) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medications',
                        'medication_name',
                        filter.medication_name,
                    ),
                };
            }
            
            if (filter.dosage) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medications',
                        'dosage',
                        filter.dosage,
                    ),
                };
            }
            
            if (filter.route) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medications',
                        'route',
                        filter.route,
                    ),
                };
            }
            
            if (filter.instructions) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medications',
                        'instructions',
                        filter.instructions,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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


      

      

      
      if (filter.accounts) {
        const listItems = filter.accounts.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          accountsId: {[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.accountsId;
        }
        

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

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

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

    
};

