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

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

        const test_items = await db.test_items.create(
            {
                id: data.id || undefined,
        
        sort_order: data.sort_order
        ||
        null
            ,
            
        points: data.points
        ||
        null
            ,
            
        override_content: data.override_content
        ||
        null
            ,
            
        is_bonus: data.is_bonus
        ||
        false
        
            ,
            
        scoring_rubric: data.scoring_rubric
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await test_items.setTest( data.test || null, {
            transaction,
        });
        
        await test_items.setSection( data.section || null, {
            transaction,
        });
        
        await test_items.setQuestion( data.question || null, {
            transaction,
        });
        

        

        

        return test_items;
    }
    

    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 test_itemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                sort_order: item.sort_order
            ||
            null
            ,
            
                points: item.points
            ||
            null
            ,
            
                override_content: item.override_content
            ||
            null
            ,
            
                is_bonus: item.is_bonus
            ||
            false
        
            ,
            
                scoring_rubric: item.scoring_rubric
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return test_items;
    }

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

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


        

        const updatePayload = {};
        
        if (data.sort_order !== undefined) updatePayload.sort_order = data.sort_order;
        
        
        if (data.points !== undefined) updatePayload.points = data.points;
        
        
        if (data.override_content !== undefined) updatePayload.override_content = data.override_content;
        
        
        if (data.is_bonus !== undefined) updatePayload.is_bonus = data.is_bonus;
        
        
        if (data.scoring_rubric !== undefined) updatePayload.scoring_rubric = data.scoring_rubric;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.test !== undefined) {
            await test_items.setTest(
              
              data.test,
              
              { transaction }
            );
        }
        
        if (data.section !== undefined) {
            await test_items.setSection(
              
              data.section,
              
              { transaction }
            );
        }
        
        if (data.question !== undefined) {
            await test_items.setQuestion(
              
              data.question,
              
              { transaction }
            );
        }
        

        
        

        

        return test_items;
    }

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

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

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


        return test_items;
    }

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

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

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

        await test_items.destroy({
            transaction
        });

        return test_items;
    }

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

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

        if (!test_items) {
            return test_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.version_items_test_item = await test_items.getVersion_items_test_item({
            transaction
        });
        
        
        
        
        
        
        
        output.matrix_rows_test_item = await test_items.getMatrix_rows_test_item({
            transaction
        });
        
        
        
        
        
        output.test = await test_items.getTest({
            transaction
        });
        
        
        output.section = await test_items.getSection({
            transaction
        });
        
        
        output.question = await test_items.getQuestion({
            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.tests,
        as: 'test',
        
        where: filter.test ? {
          [Op.or]: [
            { id: { [Op.in]: filter.test.split('|').map(term => Utils.uuid(term)) } },
            {
              title: {
                [Op.or]: filter.test.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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

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



    ];

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

            
            if (filter.override_content) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'test_items',
                        'override_content',
                        filter.override_content,
                    ),
                };
            }
            
            if (filter.scoring_rubric) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'test_items',
                        'scoring_rubric',
                        filter.scoring_rubric,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

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


      

      

      



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

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

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

    
};

