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

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

        const quiz_definitions = await db.quiz_definitions.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        difficulty: data.difficulty
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        question_count: data.question_count
        ||
        null
            ,
            
        time_limit_seconds: data.time_limit_seconds
        ||
        null
            ,
            
        generated_at: data.generated_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await quiz_definitions.setBook( data.book || null, {
            transaction,
        });
        

        

        

        return quiz_definitions;
    }
    

    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 quiz_definitionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                difficulty: item.difficulty
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                question_count: item.question_count
            ||
            null
            ,
            
                time_limit_seconds: item.time_limit_seconds
            ||
            null
            ,
            
                generated_at: item.generated_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return quiz_definitions;
    }

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

        const quiz_definitions = await db.quiz_definitions.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.difficulty !== undefined) updatePayload.difficulty = data.difficulty;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.question_count !== undefined) updatePayload.question_count = data.question_count;
        
        
        if (data.time_limit_seconds !== undefined) updatePayload.time_limit_seconds = data.time_limit_seconds;
        
        
        if (data.generated_at !== undefined) updatePayload.generated_at = data.generated_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.book !== undefined) {
            await quiz_definitions.setBook(
              
              data.book,
              
              { transaction }
            );
        }
        

        
        

        

        return quiz_definitions;
    }

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

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

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


        return quiz_definitions;
    }

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

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

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

        await quiz_definitions.destroy({
            transaction
        });

        return quiz_definitions;
    }

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

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

        if (!quiz_definitions) {
            return quiz_definitions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.quiz_questions_quiz_definition = await quiz_definitions.getQuiz_questions_quiz_definition({
            transaction
        });
        
        
        
        output.quiz_attempts_quiz_definition = await quiz_definitions.getQuiz_attempts_quiz_definition({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.book = await quiz_definitions.getBook({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        

        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

      {
        model: db.books,
        as: 'book',
        
        where: filter.book ? {
          [Op.or]: [
            { id: { [Op.in]: filter.book.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.book.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

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

            
            

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

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

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

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

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

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

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

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

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


      



            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,
                        },
                    };
                }
            }
        }
        

        

        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.quiz_definitions.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, ) {
        let where = {};
        
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'quiz_definitions',
                        'title',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

