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

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

        const medication_schedules = await db.medication_schedules.create(
            {
                id: data.id || undefined,
        
        frequency_type: data.frequency_type
        ||
        null
            ,
            
        time_of_day: data.time_of_day
        ||
        null
            ,
            
        days_of_week: data.days_of_week
        ||
        null
            ,
            
        effective_from: data.effective_from
        ||
        null
            ,
            
        effective_until: data.effective_until
        ||
        null
            ,
            
        requires_confirmation: data.requires_confirmation
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await medication_schedules.setMedication( data.medication || null, {
            transaction,
        });
        
        await medication_schedules.setPatient( data.patient || null, {
            transaction,
        });
        
        await medication_schedules.setAccounts( data.accounts || null, {
            transaction,
        });
        

        

        

        return medication_schedules;
    }
    

    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 medication_schedulesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                frequency_type: item.frequency_type
            ||
            null
            ,
            
                time_of_day: item.time_of_day
            ||
            null
            ,
            
                days_of_week: item.days_of_week
            ||
            null
            ,
            
                effective_from: item.effective_from
            ||
            null
            ,
            
                effective_until: item.effective_until
            ||
            null
            ,
            
                requires_confirmation: item.requires_confirmation
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return medication_schedules;
    }

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


        

        const updatePayload = {};
        
        if (data.frequency_type !== undefined) updatePayload.frequency_type = data.frequency_type;
        
        
        if (data.time_of_day !== undefined) updatePayload.time_of_day = data.time_of_day;
        
        
        if (data.days_of_week !== undefined) updatePayload.days_of_week = data.days_of_week;
        
        
        if (data.effective_from !== undefined) updatePayload.effective_from = data.effective_from;
        
        
        if (data.effective_until !== undefined) updatePayload.effective_until = data.effective_until;
        
        
        if (data.requires_confirmation !== undefined) updatePayload.requires_confirmation = data.requires_confirmation;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.medication !== undefined) {
            await medication_schedules.setMedication(
              
              data.medication,
              
              { transaction }
            );
        }
        
        if (data.patient !== undefined) {
            await medication_schedules.setPatient(
              
              data.patient,
              
              { transaction }
            );
        }
        
        if (data.accounts !== undefined) {
            await medication_schedules.setAccounts(
              
              data.accounts,
              
              { transaction }
            );
        }
        

        
        

        

        return medication_schedules;
    }

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

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

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


        return medication_schedules;
    }

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

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

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

        await medication_schedules.destroy({
            transaction
        });

        return medication_schedules;
    }

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

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

        if (!medication_schedules) {
            return medication_schedules;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.medication = await medication_schedules.getMedication({
            transaction
        });
        
        
        output.patient = await medication_schedules.getPatient({
            transaction
        });
        
        
        output.accounts = await medication_schedules.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.medications,
        as: 'medication',
        
        where: filter.medication ? {
          [Op.or]: [
            { id: { [Op.in]: filter.medication.split('|').map(term => Utils.uuid(term)) } },
            {
              medication_name: {
                [Op.or]: filter.medication.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        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.accounts,
        as: 'accounts',
        
      },



    ];

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

            
            if (filter.time_of_day) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medication_schedules',
                        'time_of_day',
                        filter.time_of_day,
                    ),
                };
            }
            
            if (filter.days_of_week) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'medication_schedules',
                        'days_of_week',
                        filter.days_of_week,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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


      

      

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

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

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

    
};

