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

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

        const tests = await db.tests.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        build_mode: data.build_mode
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
        target_question_count: data.target_question_count
        ||
        null
            ,
            
        target_total_points: data.target_total_points
        ||
        null
            ,
            
        target_average_difficulty: data.target_average_difficulty
        ||
        null
            ,
            
        shuffle_questions: data.shuffle_questions
        ||
        false
        
            ,
            
        shuffle_answers: data.shuffle_answers
        ||
        false
        
            ,
            
        assigned_at: data.assigned_at
        ||
        null
            ,
            
        due_at: data.due_at
        ||
        null
            ,
            
        instructions: data.instructions
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await tests.setOwner_user( data.owner_user || null, {
            transaction,
        });
        
        await tests.setSubject( data.subject || null, {
            transaction,
        });
        
        await tests.setGrade_level( data.grade_level || null, {
            transaction,
        });
        
        await tests.setTextbook( data.textbook || null, {
            transaction,
        });
        
        await tests.setChapter( data.chapter || null, {
            transaction,
        });
        

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

        

        return tests;
    }
    

    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 testsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                build_mode: item.build_mode
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
                target_question_count: item.target_question_count
            ||
            null
            ,
            
                target_total_points: item.target_total_points
            ||
            null
            ,
            
                target_average_difficulty: item.target_average_difficulty
            ||
            null
            ,
            
                shuffle_questions: item.shuffle_questions
            ||
            false
        
            ,
            
                shuffle_answers: item.shuffle_answers
            ||
            false
        
            ,
            
                assigned_at: item.assigned_at
            ||
            null
            ,
            
                due_at: item.due_at
            ||
            null
            ,
            
                instructions: item.instructions
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return tests;
    }

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

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.build_mode !== undefined) updatePayload.build_mode = data.build_mode;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        if (data.target_question_count !== undefined) updatePayload.target_question_count = data.target_question_count;
        
        
        if (data.target_total_points !== undefined) updatePayload.target_total_points = data.target_total_points;
        
        
        if (data.target_average_difficulty !== undefined) updatePayload.target_average_difficulty = data.target_average_difficulty;
        
        
        if (data.shuffle_questions !== undefined) updatePayload.shuffle_questions = data.shuffle_questions;
        
        
        if (data.shuffle_answers !== undefined) updatePayload.shuffle_answers = data.shuffle_answers;
        
        
        if (data.assigned_at !== undefined) updatePayload.assigned_at = data.assigned_at;
        
        
        if (data.due_at !== undefined) updatePayload.due_at = data.due_at;
        
        
        if (data.instructions !== undefined) updatePayload.instructions = data.instructions;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.owner_user !== undefined) {
            await tests.setOwner_user(
              
              data.owner_user,
              
              { transaction }
            );
        }
        
        if (data.subject !== undefined) {
            await tests.setSubject(
              
              data.subject,
              
              { transaction }
            );
        }
        
        if (data.grade_level !== undefined) {
            await tests.setGrade_level(
              
              data.grade_level,
              
              { transaction }
            );
        }
        
        if (data.textbook !== undefined) {
            await tests.setTextbook(
              
              data.textbook,
              
              { transaction }
            );
        }
        
        if (data.chapter !== undefined) {
            await tests.setChapter(
              
              data.chapter,
              
              { transaction }
            );
        }
        

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

        

        return tests;
    }

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

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

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


        return tests;
    }

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

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

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

        await tests.destroy({
            transaction
        });

        return tests;
    }

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

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

        if (!tests) {
            return tests;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.test_sections_test = await tests.getTest_sections_test({
            transaction
        });
        
        
        output.test_items_test = await tests.getTest_items_test({
            transaction
        });
        
        
        output.test_versions_test = await tests.getTest_versions_test({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        output.owner_user = await tests.getOwner_user({
            transaction
        });
        
        
        output.subject = await tests.getSubject({
            transaction
        });
        
        
        output.grade_level = await tests.getGrade_level({
            transaction
        });
        
        
        output.textbook = await tests.getTextbook({
            transaction
        });
        
        
        output.chapter = await tests.getChapter({
            transaction
        });
        
        
        output.skills = await tests.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.users,
        as: 'owner_user',
        
        where: filter.owner_user ? {
          [Op.or]: [
            { id: { [Op.in]: filter.owner_user.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.owner_user.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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

      {
        model: db.textbooks,
        as: 'textbook',
        
        where: filter.textbook ? {
          [Op.or]: [
            { id: { [Op.in]: filter.textbook.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.textbook.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,
      },


    ];

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

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

            
            
            if (filter.calendarStart && filter.calendarEnd) {
                where = {
                    ...where,
                    [Op.or]: [
                        {
                            assigned_at: {
                                [Op.between]: [filter.calendarStart, filter.calendarEnd],
                            },
                    },
                {
                    due_at: {
                        [Op.between]: [filter.calendarStart, filter.calendarEnd],
                    },
                },
                ],
            };
            }
            

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

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

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

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

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

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

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

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

                if (end !== undefined && end !== null && end !== '') {
                    where = {
                        ...where,
                    assigned_at: {
                    ...where.assigned_at,
                            [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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

            
            if (filter.build_mode) {
                where = {
                    ...where,
                build_mode: filter.build_mode,
            };
            }
            
            if (filter.status) {
                where = {
                    ...where,
                status: filter.status,
            };
            }
            
            if (filter.shuffle_questions) {
                where = {
                    ...where,
                shuffle_questions: filter.shuffle_questions,
            };
            }
            
            if (filter.shuffle_answers) {
                where = {
                    ...where,
                shuffle_answers: filter.shuffle_answers,
            };
            }
            


      

      

      

      

      


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

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

    
};

