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

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

        const assignments = await db.assignments.create(
            {
                id: data.id || undefined,
        
        title: data.title
        ||
        null
            ,
            
        description: data.description
        ||
        null
            ,
            
        assigned_at: data.assigned_at
        ||
        null
            ,
            
        due_at: data.due_at
        ||
        null
            ,
            
        max_points: data.max_points
        ||
        null
            ,
            
        status: data.status
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

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

        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.assignments.getTableName(),
                belongsToColumn: 'attachments',
                belongsToId: assignments.id,
            },
            data.attachments,
            options,
        );
        

        return assignments;
    }
    

    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 assignmentsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                title: item.title
            ||
            null
            ,
            
                description: item.description
            ||
            null
            ,
            
                assigned_at: item.assigned_at
            ||
            null
            ,
            
                due_at: item.due_at
            ||
            null
            ,
            
                max_points: item.max_points
            ||
            null
            ,
            
                status: item.status
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        
        for (let i = 0; i < assignments.length; i++) {
            await FileDBApi.replaceRelationFiles(
                {
                    belongsTo: db.assignments.getTableName(),
                    belongsToColumn: 'attachments',
                    belongsToId: assignments[i].id,
                },
                data[i].attachments,
                options,
            );
        }
        

        return assignments;
    }

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

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


        

        const updatePayload = {};
        
        if (data.title !== undefined) updatePayload.title = data.title;
        
        
        if (data.description !== undefined) updatePayload.description = data.description;
        
        
        if (data.assigned_at !== undefined) updatePayload.assigned_at = data.assigned_at;
        
        
        if (data.due_at !== undefined) updatePayload.due_at = data.due_at;
        
        
        if (data.max_points !== undefined) updatePayload.max_points = data.max_points;
        
        
        if (data.status !== undefined) updatePayload.status = data.status;
        
        
        updatePayload.updatedById = currentUser.id;

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

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

        
        

        
        await FileDBApi.replaceRelationFiles(
            {
                belongsTo: db.assignments.getTableName(),
                belongsToColumn: 'attachments',
                belongsToId: assignments.id,
            },
            data.attachments,
            options,
        );
        

        return assignments;
    }

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

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

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


        return assignments;
    }

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

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

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

        await assignments.destroy({
            transaction
        });

        return assignments;
    }

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

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

        if (!assignments) {
            return assignments;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.submissions_assignment = await assignments.getSubmissions_assignment({
            transaction
        });
        
        
        
        
        
        
        
        
        
        output.course_section = await assignments.getCourse_section({
            transaction
        });
        
        
        output.teacher = await assignments.getTeacher({
            transaction
        });
        
        
        output.attachments = await assignments.getAttachments({
            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}%` }))
              }
            },
          ]
        } : {},
        
      },



      {
        model: db.file,
        as: 'attachments',
      },

    ];

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

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

            
            
            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.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.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.active !== undefined) {
                where = {
                    ...where,
                    active: filter.active === true || filter.active === 'true'
                };
            }

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


      

      



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

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

    
};

