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

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

        const quizzes = await db.quizzes.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        quiz_type: data.quiz_type
        ||
        null
            ,
            
        visibility: data.visibility
        ||
        null
            ,
            
        is_verified: data.is_verified
        ||
        false
        
            ,
            
        verified_badge_text: data.verified_badge_text
        ||
        null
            ,
            
        subject: data.subject
        ||
        null
            ,
            
        age_group: data.age_group
        ||
        null
            ,
            
        difficulty: data.difficulty
        ||
        null
            ,
            
        allow_images_in_questions: data.allow_images_in_questions
        ||
        false
        
            ,
            
        published_at: data.published_at
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await quizzes.setOwner( data.owner || null, {
            transaction,
        });
        

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.quizzes.getTableName(),
                belongsToColumn: 'cover_images',
                belongsToId: quizzes.id,
            },
            data.cover_images,
            options,
        );
        

        return quizzes;
    }
    

    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 quizzesData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                quiz_type: item.quiz_type
            ||
            null
            ,
            
                visibility: item.visibility
            ||
            null
            ,
            
                is_verified: item.is_verified
            ||
            false
        
            ,
            
                verified_badge_text: item.verified_badge_text
            ||
            null
            ,
            
                subject: item.subject
            ||
            null
            ,
            
                age_group: item.age_group
            ||
            null
            ,
            
                difficulty: item.difficulty
            ||
            null
            ,
            
                allow_images_in_questions: item.allow_images_in_questions
            ||
            false
        
            ,
            
                published_at: item.published_at
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < quizzes.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.quizzes.getTableName(),
                    belongsToColumn: 'cover_images',
                    belongsToId: quizzes[i].id,
                },
                data[i].cover_images,
                options,
            );
        }
        

        return quizzes;
    }

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

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.quiz_type !== undefined) updatePayload.quiz_type = data.quiz_type;
        
        
        if (data.visibility !== undefined) updatePayload.visibility = data.visibility;
        
        
        if (data.is_verified !== undefined) updatePayload.is_verified = data.is_verified;
        
        
        if (data.verified_badge_text !== undefined) updatePayload.verified_badge_text = data.verified_badge_text;
        
        
        if (data.subject !== undefined) updatePayload.subject = data.subject;
        
        
        if (data.age_group !== undefined) updatePayload.age_group = data.age_group;
        
        
        if (data.difficulty !== undefined) updatePayload.difficulty = data.difficulty;
        
        
        if (data.allow_images_in_questions !== undefined) updatePayload.allow_images_in_questions = data.allow_images_in_questions;
        
        
        if (data.published_at !== undefined) updatePayload.published_at = data.published_at;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.owner !== undefined) {
            await quizzes.setOwner(
              
              data.owner,
              
              { transaction }
            );
        }
        

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.quizzes.getTableName(),
                belongsToColumn: 'cover_images',
                belongsToId: quizzes.id,
            },
            data.cover_images,
            options,
        );
        

        return quizzes;
    }

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

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

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


        return quizzes;
    }

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

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

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

        await quizzes.destroy({
            transaction
        });

        return quizzes;
    }

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

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

        if (!quizzes) {
            return quizzes;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.quiz_questions_quiz = await quizzes.getQuiz_questions_quiz({
            transaction
        });
        
        
        
        
        output.quiz_tag_links_quiz = await quizzes.getQuiz_tag_links_quiz({
            transaction
        });
        
        
        output.orbix_quiz_assistant_sessions_generated_quiz = await quizzes.getOrbix_quiz_assistant_sessions_generated_quiz({
            transaction
        });
        
        
        
        output.matches_quiz = await quizzes.getMatches_quiz({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.owner = await quizzes.getOwner({
            transaction
        });
        
        
        output.cover_images = await quizzes.getCover_images({
            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.users,
        as: 'owner',
        
        where: filter.owner ? {
          [Op.or]: [
            { id: { [Op.in]: filter.owner.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.owner.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },



      {
        model: db.file,
        as: 'cover_images',
      },

    ];

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

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

            
            

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

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

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

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

            
            if (filter.quiz_type) {
                where = {
                    ...where,
                quiz_type: filter.quiz_type,
            };
            }
            
            if (filter.visibility) {
                where = {
                    ...where,
                visibility: filter.visibility,
            };
            }
            
            if (filter.is_verified) {
                where = {
                    ...where,
                is_verified: filter.is_verified,
            };
            }
            
            if (filter.subject) {
                where = {
                    ...where,
                subject: filter.subject,
            };
            }
            
            if (filter.age_group) {
                where = {
                    ...where,
                age_group: filter.age_group,
            };
            }
            
            if (filter.difficulty) {
                where = {
                    ...where,
                difficulty: filter.difficulty,
            };
            }
            
            if (filter.allow_images_in_questions) {
                where = {
                    ...where,
                allow_images_in_questions: filter.allow_images_in_questions,
            };
            }
            


      



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

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

    
};

