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

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

        const dashboard_snapshots = await db.dashboard_snapshots.create(
            {
                id: data.id || undefined,
        
        snapshot_at: data.snapshot_at
        ||
        null
            ,
            
        study_hours_last_7d: data.study_hours_last_7d
        ||
        null
            ,
            
        study_hours_last_30d: data.study_hours_last_30d
        ||
        null
            ,
            
        retention_estimate: data.retention_estimate
        ||
        null
            ,
            
        test_performance_avg: data.test_performance_avg
        ||
        null
            ,
            
        cards_due_count: data.cards_due_count
        ||
        null
            ,
            
        streak_days: data.streak_days
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await dashboard_snapshots.setUser( data.user || null, {
            transaction,
        });
        
        await dashboard_snapshots.setWorkspace( data.workspace || null, {
            transaction,
        });
        
        await dashboard_snapshots.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return dashboard_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 dashboard_snapshotsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                snapshot_at: item.snapshot_at
            ||
            null
            ,
            
                study_hours_last_7d: item.study_hours_last_7d
            ||
            null
            ,
            
                study_hours_last_30d: item.study_hours_last_30d
            ||
            null
            ,
            
                retention_estimate: item.retention_estimate
            ||
            null
            ,
            
                test_performance_avg: item.test_performance_avg
            ||
            null
            ,
            
                cards_due_count: item.cards_due_count
            ||
            null
            ,
            
                streak_days: item.streak_days
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

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


        

        const updatePayload = {};
        
        if (data.snapshot_at !== undefined) updatePayload.snapshot_at = data.snapshot_at;
        
        
        if (data.study_hours_last_7d !== undefined) updatePayload.study_hours_last_7d = data.study_hours_last_7d;
        
        
        if (data.study_hours_last_30d !== undefined) updatePayload.study_hours_last_30d = data.study_hours_last_30d;
        
        
        if (data.retention_estimate !== undefined) updatePayload.retention_estimate = data.retention_estimate;
        
        
        if (data.test_performance_avg !== undefined) updatePayload.test_performance_avg = data.test_performance_avg;
        
        
        if (data.cards_due_count !== undefined) updatePayload.cards_due_count = data.cards_due_count;
        
        
        if (data.streak_days !== undefined) updatePayload.streak_days = data.streak_days;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await dashboard_snapshots.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.workspace !== undefined) {
            await dashboard_snapshots.setWorkspace(
              
              data.workspace,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await dashboard_snapshots.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return dashboard_snapshots;
    }

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

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

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


        return dashboard_snapshots;
    }

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

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

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

        await dashboard_snapshots.destroy({
            transaction
        });

        return dashboard_snapshots;
    }

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

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

        if (!dashboard_snapshots) {
            return dashboard_snapshots;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await dashboard_snapshots.getUser({
            transaction
        });
        
        
        output.workspace = await dashboard_snapshots.getWorkspace({
            transaction
        });
        
        
        output.organizations = await dashboard_snapshots.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.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.workspaces,
        as: 'workspace',
        
        where: filter.workspace ? {
          [Op.or]: [
            { id: { [Op.in]: filter.workspace.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.workspace.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            

            
            

            
            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.study_hours_last_7dRange) {
                const [start, end] = filter.study_hours_last_7dRange;

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

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

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

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

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

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

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

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

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

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

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

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

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

            


      

      

      
      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.dashboard_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(
                        'dashboard_snapshots',
                        'retention_estimate',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

