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

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

        const admin_metrics_snapshots = await db.admin_metrics_snapshots.create(
            {
                id: data.id || undefined,
        
        snapshot_at: data.snapshot_at
        ||
        null
            ,
            
        total_accounts: data.total_accounts
        ||
        null
            ,
            
        total_users: data.total_users
        ||
        null
            ,
            
        total_patients: data.total_patients
        ||
        null
            ,
            
        active_devices: data.active_devices
        ||
        null
            ,
            
        alerts_last_24h: data.alerts_last_24h
        ||
        null
            ,
            
        cognitive_sessions_last_7d: data.cognitive_sessions_last_7d
        ||
        null
            ,
            
        reminders_sent_last_24h: data.reminders_sent_last_24h
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await admin_metrics_snapshots.setAccounts( data.accounts || null, {
            transaction,
        });
        

        

        

        return admin_metrics_snapshots;
    }
    

    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 admin_metrics_snapshotsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                snapshot_at: item.snapshot_at
            ||
            null
            ,
            
                total_accounts: item.total_accounts
            ||
            null
            ,
            
                total_users: item.total_users
            ||
            null
            ,
            
                total_patients: item.total_patients
            ||
            null
            ,
            
                active_devices: item.active_devices
            ||
            null
            ,
            
                alerts_last_24h: item.alerts_last_24h
            ||
            null
            ,
            
                cognitive_sessions_last_7d: item.cognitive_sessions_last_7d
            ||
            null
            ,
            
                reminders_sent_last_24h: item.reminders_sent_last_24h
            ||
            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 admin_metrics_snapshots = await db.admin_metrics_snapshots.bulkCreate(admin_metrics_snapshotsData, { transaction });

        // For each item created, replace relation files
        

        return admin_metrics_snapshots;
    }

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


        

        const updatePayload = {};
        
        if (data.snapshot_at !== undefined) updatePayload.snapshot_at = data.snapshot_at;
        
        
        if (data.total_accounts !== undefined) updatePayload.total_accounts = data.total_accounts;
        
        
        if (data.total_users !== undefined) updatePayload.total_users = data.total_users;
        
        
        if (data.total_patients !== undefined) updatePayload.total_patients = data.total_patients;
        
        
        if (data.active_devices !== undefined) updatePayload.active_devices = data.active_devices;
        
        
        if (data.alerts_last_24h !== undefined) updatePayload.alerts_last_24h = data.alerts_last_24h;
        
        
        if (data.cognitive_sessions_last_7d !== undefined) updatePayload.cognitive_sessions_last_7d = data.cognitive_sessions_last_7d;
        
        
        if (data.reminders_sent_last_24h !== undefined) updatePayload.reminders_sent_last_24h = data.reminders_sent_last_24h;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.accounts !== undefined) {
            await admin_metrics_snapshots.setAccounts(
              
              data.accounts,
              
              { transaction }
            );
        }
        

        
        

        

        return admin_metrics_snapshots;
    }

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

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

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


        return admin_metrics_snapshots;
    }

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

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

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

        await admin_metrics_snapshots.destroy({
            transaction
        });

        return admin_metrics_snapshots;
    }

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

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

        if (!admin_metrics_snapshots) {
            return admin_metrics_snapshots;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.accounts = await admin_metrics_snapshots.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.accounts,
        as: 'accounts',
        
      },



    ];

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

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

            
            

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            


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

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

    
};

