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

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

        const grade_items = await db.grade_items.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
        category: data.category
        ||
        null
            ,
            
        weight: data.weight
        ||
        null
            ,
            
        max_points: data.max_points
        ||
        null
            ,
            
        assigned_at: data.assigned_at
        ||
        null
            ,
            
        due_at: data.due_at
        ||
        null
            ,
            
        published: data.published
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await grade_items.setCourse_section( data.course_section || null, {
            transaction,
        });
        
        await grade_items.setTeacher( data.teacher || null, {
            transaction,
        });
        

        

        

        return grade_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 grade_itemsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                name: item.name
            ||
            null
            ,
            
                category: item.category
            ||
            null
            ,
            
                weight: item.weight
            ||
            null
            ,
            
                max_points: item.max_points
            ||
            null
            ,
            
                assigned_at: item.assigned_at
            ||
            null
            ,
            
                due_at: item.due_at
            ||
            null
            ,
            
                published: item.published
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return grade_items;
    }

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

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


        

        const updatePayload = {};
        
        if (data.name !== undefined) updatePayload.name = data.name;
        
        
        if (data.category !== undefined) updatePayload.category = data.category;
        
        
        if (data.weight !== undefined) updatePayload.weight = data.weight;
        
        
        if (data.max_points !== undefined) updatePayload.max_points = data.max_points;
        
        
        if (data.assigned_at !== undefined) updatePayload.assigned_at = data.assigned_at;
        
        
        if (data.due_at !== undefined) updatePayload.due_at = data.due_at;
        
        
        if (data.published !== undefined) updatePayload.published = data.published;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.course_section !== undefined) {
            await grade_items.setCourse_section(
              
              data.course_section,
              
              { transaction }
            );
        }
        
        if (data.teacher !== undefined) {
            await grade_items.setTeacher(
              
              data.teacher,
              
              { transaction }
            );
        }
        

        
        

        

        return grade_items;
    }

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

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

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


        return grade_items;
    }

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

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

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

        await grade_items.destroy({
            transaction
        });

        return grade_items;
    }

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

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

        if (!grade_items) {
            return grade_items;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.grade_records_grade_item = await grade_items.getGrade_records_grade_item({
            transaction
        });
        
        
        
        
        
        
        
        output.course_section = await grade_items.getCourse_section({
            transaction
        });
        
        
        output.teacher = await grade_items.getTeacher({
            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.course_sections,
        as: 'course_section',
        
        where: filter.course_section ? {
          [Op.or]: [
            { id: { [Op.in]: filter.course_section.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.course_section.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

      {
        model: db.teachers,
        as: 'teacher',
        
        where: filter.teacher ? {
          [Op.or]: [
            { id: { [Op.in]: filter.teacher.split('|').map(term => Utils.uuid(term)) } },
            {
              employee_number: {
                [Op.or]: filter.teacher.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(
                        'grade_items',
                        'name',
                        filter.name,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      

      



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

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

    
};

