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

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

        const patient_access_grants = await db.patient_access_grants.create(
            {
                id: data.id || undefined,
        
        access_level: data.access_level
        ||
        null
            ,
            
        can_view_iot_location: data.can_view_iot_location
        ||
        false
        
            ,
            
        can_manage_medications: data.can_manage_medications
        ||
        false
        
            ,
            
        can_manage_calendar: data.can_manage_calendar
        ||
        false
        
            ,
            
        can_view_health_data: data.can_view_health_data
        ||
        false
        
            ,
            
        granted_at: data.granted_at
        ||
        null
            ,
            
        revoked_at: data.revoked_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await patient_access_grants.setPatient( data.patient || null, {
            transaction,
        });
        
        await patient_access_grants.setUser( data.user || null, {
            transaction,
        });
        
        await patient_access_grants.setAccounts( data.accounts || null, {
            transaction,
        });
        

        

        

        return patient_access_grants;
    }
    

    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 patient_access_grantsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                access_level: item.access_level
            ||
            null
            ,
            
                can_view_iot_location: item.can_view_iot_location
            ||
            false
        
            ,
            
                can_manage_medications: item.can_manage_medications
            ||
            false
        
            ,
            
                can_manage_calendar: item.can_manage_calendar
            ||
            false
        
            ,
            
                can_view_health_data: item.can_view_health_data
            ||
            false
        
            ,
            
                granted_at: item.granted_at
            ||
            null
            ,
            
                revoked_at: item.revoked_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return patient_access_grants;
    }

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


        

        const updatePayload = {};
        
        if (data.access_level !== undefined) updatePayload.access_level = data.access_level;
        
        
        if (data.can_view_iot_location !== undefined) updatePayload.can_view_iot_location = data.can_view_iot_location;
        
        
        if (data.can_manage_medications !== undefined) updatePayload.can_manage_medications = data.can_manage_medications;
        
        
        if (data.can_manage_calendar !== undefined) updatePayload.can_manage_calendar = data.can_manage_calendar;
        
        
        if (data.can_view_health_data !== undefined) updatePayload.can_view_health_data = data.can_view_health_data;
        
        
        if (data.granted_at !== undefined) updatePayload.granted_at = data.granted_at;
        
        
        if (data.revoked_at !== undefined) updatePayload.revoked_at = data.revoked_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.patient !== undefined) {
            await patient_access_grants.setPatient(
              
              data.patient,
              
              { transaction }
            );
        }
        
        if (data.user !== undefined) {
            await patient_access_grants.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.accounts !== undefined) {
            await patient_access_grants.setAccounts(
              
              data.accounts,
              
              { transaction }
            );
        }
        

        
        

        

        return patient_access_grants;
    }

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

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

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


        return patient_access_grants;
    }

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

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

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

        await patient_access_grants.destroy({
            transaction
        });

        return patient_access_grants;
    }

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

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

        if (!patient_access_grants) {
            return patient_access_grants;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.patient = await patient_access_grants.getPatient({
            transaction
        });
        
        
        output.user = await patient_access_grants.getUser({
            transaction
        });
        
        
        output.accounts = await patient_access_grants.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: 'user',
        
        where: filter.user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.user.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.granted_atRange) {
                const [start, end] = filter.granted_atRange;

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

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

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

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

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

            
            if (filter.access_level) {
                where = {
                    ...where,
                access_level: filter.access_level,
            };
            }
            
            if (filter.can_view_iot_location) {
                where = {
                    ...where,
                can_view_iot_location: filter.can_view_iot_location,
            };
            }
            
            if (filter.can_manage_medications) {
                where = {
                    ...where,
                can_manage_medications: filter.can_manage_medications,
            };
            }
            
            if (filter.can_manage_calendar) {
                where = {
                    ...where,
                can_manage_calendar: filter.can_manage_calendar,
            };
            }
            
            if (filter.can_view_health_data) {
                where = {
                    ...where,
                can_view_health_data: filter.can_view_health_data,
            };
            }
            


      

      

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

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

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

    
};

