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

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

        const questions = await db.questions.create(
            {
                id: data.id || undefined,
        
        question_type: data.question_type
        ||
        null
            ,
            
        difficulty: data.difficulty
        ||
        null
            ,
            
        content: data.content
        ||
        null
            ,
            
        default_points: data.default_points
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
        hint: data.hint
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await questions.setQuestion_bank( data.question_bank || null, {
            transaction,
        });
        
        await questions.setChapter( data.chapter || null, {
            transaction,
        });
        

        
        await questions.setSkills(data.skills || [], {
            transaction,
        });
        

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

        return questions;
    }
    

    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 questionsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                question_type: item.question_type
            ||
            null
            ,
            
                difficulty: item.difficulty
            ||
            null
            ,
            
                content: item.content
            ||
            null
            ,
            
                default_points: item.default_points
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
                hint: item.hint
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

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

        return questions;
    }

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

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


        

        const updatePayload = {};
        
        if (data.question_type !== undefined) updatePayload.question_type = data.question_type;
        
        
        if (data.difficulty !== undefined) updatePayload.difficulty = data.difficulty;
        
        
        if (data.content !== undefined) updatePayload.content = data.content;
        
        
        if (data.default_points !== undefined) updatePayload.default_points = data.default_points;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        if (data.hint !== undefined) updatePayload.hint = data.hint;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.question_bank !== undefined) {
            await questions.setQuestion_bank(
              
              data.question_bank,
              
              { transaction }
            );
        }
        
        if (data.chapter !== undefined) {
            await questions.setChapter(
              
              data.chapter,
              
              { transaction }
            );
        }
        

        
        
        if (data.skills !== undefined) {
            await questions.setSkills(data.skills, { transaction });
        }
        

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

        return questions;
    }

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

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

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


        return questions;
    }

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

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

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

        await questions.destroy({
            transaction
        });

        return questions;
    }

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

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

        if (!questions) {
            return questions;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        output.answer_choices_question = await questions.getAnswer_choices_question({
            transaction
        });
        
        
        
        
        output.test_items_question = await questions.getTest_items_question({
            transaction
        });
        
        
        
        
        output.version_answer_orders_question = await questions.getVersion_answer_orders_question({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        output.question_bank = await questions.getQuestion_bank({
            transaction
        });
        
        
        output.chapter = await questions.getChapter({
            transaction
        });
        
        
        output.images = await questions.getImages({
            transaction
        });
        
        
        output.attachments = await questions.getAttachments({
            transaction
        });
        
        
        output.skills = await questions.getSkills({
            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.question_banks,
        as: 'question_bank',
        
        where: filter.question_bank ? {
          [Op.or]: [
            { id: { [Op.in]: filter.question_bank.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.question_bank.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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


      {
        model: db.skills,
        as: 'skills',
        required: false,
      },


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

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

    ];

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

            
            if (filter.content) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'questions',
                        'content',
                        filter.content,
                    ),
                };
            }
            
            if (filter.hint) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'questions',
                        'hint',
                        filter.hint,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      

      


      if (filter.skills) {
        const searchTerms = filter.skills.split('|');

        include = [
          {
            model: db.skills,
            as: 'skills_filter',
            required: searchTerms.length > 0,
            where: searchTerms.length > 0 ? {
              [Op.or]: [
                { id: { [Op.in]: searchTerms.map(term => Utils.uuid(term)) } },
                { 
                  name: {
                    [Op.or]: searchTerms.map(term => ({ [Op.iLike]: `%${term}%` }))
                  }
                }
              ]
            } : undefined
          },
          ...include,
        ]
      }


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

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

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

    
};

