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

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

        const question_banks = await db.question_banks.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        is_public: data.is_public
        ||
        false
        
            ,
            
        description: data.description
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        

        return question_banks;
    }
    

    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 question_banksData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                is_public: item.is_public
            ||
            false
        
            ,
            
                description: item.description
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return question_banks;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.is_public !== undefined) updatePayload.is_public = data.is_public;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        

        return question_banks;
    }

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

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

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


        return question_banks;
    }

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

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

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

        await question_banks.destroy({
            transaction
        });

        return question_banks;
    }

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

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

        if (!question_banks) {
            return question_banks;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        output.questions_question_bank = await question_banks.getQuestions_question_bank({
            transaction
        });
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.subject = await question_banks.getSubject({
            transaction
        });
        
        
        output.grade_level = await question_banks.getGrade_level({
            transaction
        });
        
        
        output.textbook = await question_banks.getTextbook({
            transaction
        });
        
        
        output.owner_user = await question_banks.getOwner_user({
            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.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.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}%` }))
              }
            },
          ]
        } : {},
        
      },



    ];

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

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

            
            

            

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

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


      

      

      

      



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

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

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

    
};

