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

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

        const spaced_repetition_states = await db.spaced_repetition_states.create(
            {
                id: data.id || undefined,
        
        algorithm: data.algorithm
        ||
        null
            ,
            
        repetitions: data.repetitions
        ||
        null
            ,
            
        lapses: data.lapses
        ||
        null
            ,
            
        ease_factor: data.ease_factor
        ||
        null
            ,
            
        interval_days: data.interval_days
        ||
        null
            ,
            
        stability: data.stability
        ||
        null
            ,
            
        difficulty: data.difficulty
        ||
        null
            ,
            
        due_at: data.due_at
        ||
        null
            ,
            
        last_reviewed_at: data.last_reviewed_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await spaced_repetition_states.setUser( data.user || null, {
            transaction,
        });
        
        await spaced_repetition_states.setFlashcard( data.flashcard || null, {
            transaction,
        });
        
        await spaced_repetition_states.setOrganizations( data.organizations || null, {
            transaction,
        });
        

        

        

        return spaced_repetition_states;
    }
    

    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 spaced_repetition_statesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                algorithm: item.algorithm
            ||
            null
            ,
            
                repetitions: item.repetitions
            ||
            null
            ,
            
                lapses: item.lapses
            ||
            null
            ,
            
                ease_factor: item.ease_factor
            ||
            null
            ,
            
                interval_days: item.interval_days
            ||
            null
            ,
            
                stability: item.stability
            ||
            null
            ,
            
                difficulty: item.difficulty
            ||
            null
            ,
            
                due_at: item.due_at
            ||
            null
            ,
            
                last_reviewed_at: item.last_reviewed_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return spaced_repetition_states;
    }

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


        

        const updatePayload = {};
        
        if (data.algorithm !== undefined) updatePayload.algorithm = data.algorithm;
        
        
        if (data.repetitions !== undefined) updatePayload.repetitions = data.repetitions;
        
        
        if (data.lapses !== undefined) updatePayload.lapses = data.lapses;
        
        
        if (data.ease_factor !== undefined) updatePayload.ease_factor = data.ease_factor;
        
        
        if (data.interval_days !== undefined) updatePayload.interval_days = data.interval_days;
        
        
        if (data.stability !== undefined) updatePayload.stability = data.stability;
        
        
        if (data.difficulty !== undefined) updatePayload.difficulty = data.difficulty;
        
        
        if (data.due_at !== undefined) updatePayload.due_at = data.due_at;
        
        
        if (data.last_reviewed_at !== undefined) updatePayload.last_reviewed_at = data.last_reviewed_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.user !== undefined) {
            await spaced_repetition_states.setUser(
              
              data.user,
              
              { transaction }
            );
        }
        
        if (data.flashcard !== undefined) {
            await spaced_repetition_states.setFlashcard(
              
              data.flashcard,
              
              { transaction }
            );
        }
        
        if (data.organizations !== undefined) {
            await spaced_repetition_states.setOrganizations(
              
              data.organizations,
              
              { transaction }
            );
        }
        

        
        

        

        return spaced_repetition_states;
    }

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

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

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


        return spaced_repetition_states;
    }

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

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

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

        await spaced_repetition_states.destroy({
            transaction
        });

        return spaced_repetition_states;
    }

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

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

        if (!spaced_repetition_states) {
            return spaced_repetition_states;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.user = await spaced_repetition_states.getUser({
            transaction
        });
        
        
        output.flashcard = await spaced_repetition_states.getFlashcard({
            transaction
        });
        
        
        output.organizations = await spaced_repetition_states.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.flashcards,
        as: 'flashcard',
        
        where: filter.flashcard ? {
          [Op.or]: [
            { id: { [Op.in]: filter.flashcard.split('|').map(term => Utils.uuid(term)) } },
            {
              front: {
                [Op.or]: filter.flashcard.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.repetitionsRange) {
                const [start, end] = filter.repetitionsRange;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


      

      

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

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

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

    
};

