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

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

        const grade_records = await db.grade_records.create(
            {
                id: data.id || undefined,
        
        score: data.score
        ||
        null
            ,
            
        letter_grade: data.letter_grade
        ||
        null
            ,
            
        graded_at: data.graded_at
        ||
        null
            ,
            
        comment: data.comment
        ||
        null
            ,
            
        published: data.published
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await grade_records.setGrade_item( data.grade_item || null, {
            transaction,
        });
        
        await grade_records.setStudent( data.student || null, {
            transaction,
        });
        

        

        

        return grade_records;
    }
    

    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_recordsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                score: item.score
            ||
            null
            ,
            
                letter_grade: item.letter_grade
            ||
            null
            ,
            
                graded_at: item.graded_at
            ||
            null
            ,
            
                comment: item.comment
            ||
            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_records = await db.grade_records.bulkCreate(grade_recordsData, { transaction });

        // For each item created, replace relation files
        

        return grade_records;
    }

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

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


        

        const updatePayload = {};
        
        if (data.score !== undefined) updatePayload.score = data.score;
        
        
        if (data.letter_grade !== undefined) updatePayload.letter_grade = data.letter_grade;
        
        
        if (data.graded_at !== undefined) updatePayload.graded_at = data.graded_at;
        
        
        if (data.comment !== undefined) updatePayload.comment = data.comment;
        
        
        if (data.published !== undefined) updatePayload.published = data.published;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.grade_item !== undefined) {
            await grade_records.setGrade_item(
              
              data.grade_item,
              
              { transaction }
            );
        }
        
        if (data.student !== undefined) {
            await grade_records.setStudent(
              
              data.student,
              
              { transaction }
            );
        }
        

        
        

        

        return grade_records;
    }

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

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

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


        return grade_records;
    }

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

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

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

        await grade_records.destroy({
            transaction
        });

        return grade_records;
    }

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

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

        if (!grade_records) {
            return grade_records;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.grade_item = await grade_records.getGrade_item({
            transaction
        });
        
        
        output.student = await grade_records.getStudent({
            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.grade_items,
        as: 'grade_item',
        
        where: filter.grade_item ? {
          [Op.or]: [
            { id: { [Op.in]: filter.grade_item.split('|').map(term => Utils.uuid(term)) } },
            {
              name: {
                [Op.or]: filter.grade_item.split('|').map(term => ({ [Op.iLike]: `%${term}%` }))
              }
            },
          ]
        } : {},
        
      },

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



    ];

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

            
            if (filter.comment) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'grade_records',
                        'comment',
                        filter.comment,
                    ),
                };
            }
            

            
            

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

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

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

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

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

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

            
            if (filter.letter_grade) {
                where = {
                    ...where,
                letter_grade: filter.letter_grade,
            };
            }
            
            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_records.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_records',
                        'letter_grade',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

