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

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

        const teaching_assignments = await db.teaching_assignments.create(
            {
                id: data.id || undefined,
        
        assignment_role: data.assignment_role
        ||
        null
            ,
            
        assigned_at: data.assigned_at
        ||
        null
            ,
            
        is_active: data.is_active
        ||
        false
        
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await teaching_assignments.setTeacher( data.teacher || null, {
            transaction,
        });
        
        await teaching_assignments.setClassroom( data.classroom || null, {
            transaction,
        });
        
        await teaching_assignments.setSubject( data.subject || null, {
            transaction,
        });
        
        await teaching_assignments.setAssigned_by( data.assigned_by || null, {
            transaction,
        });
        
        await teaching_assignments.setSchools( data.schools || null, {
            transaction,
        });
        

        

        

        return teaching_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 teaching_assignmentsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                assignment_role: item.assignment_role
            ||
            null
            ,
            
                assigned_at: item.assigned_at
            ||
            null
            ,
            
                is_active: item.is_active
            ||
            false
        
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return teaching_assignments;
    }

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

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


        

        const updatePayload = {};
        
        if (data.assignment_role !== undefined) updatePayload.assignment_role = data.assignment_role;
        
        
        if (data.assigned_at !== undefined) updatePayload.assigned_at = data.assigned_at;
        
        
        if (data.is_active !== undefined) updatePayload.is_active = data.is_active;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.teacher !== undefined) {
            await teaching_assignments.setTeacher(
              
              data.teacher,
              
              { transaction }
            );
        }
        
        if (data.classroom !== undefined) {
            await teaching_assignments.setClassroom(
              
              data.classroom,
              
              { transaction }
            );
        }
        
        if (data.subject !== undefined) {
            await teaching_assignments.setSubject(
              
              data.subject,
              
              { transaction }
            );
        }
        
        if (data.assigned_by !== undefined) {
            await teaching_assignments.setAssigned_by(
              
              data.assigned_by,
              
              { transaction }
            );
        }
        
        if (data.schools !== undefined) {
            await teaching_assignments.setSchools(
              
              data.schools,
              
              { transaction }
            );
        }
        

        
        

        

        return teaching_assignments;
    }

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

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

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


        return teaching_assignments;
    }

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

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

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

        await teaching_assignments.destroy({
            transaction
        });

        return teaching_assignments;
    }

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

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

        if (!teaching_assignments) {
            return teaching_assignments;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.teacher = await teaching_assignments.getTeacher({
            transaction
        });
        
        
        output.classroom = await teaching_assignments.getClassroom({
            transaction
        });
        
        
        output.subject = await teaching_assignments.getSubject({
            transaction
        });
        
        
        output.assigned_by = await teaching_assignments.getAssigned_by({
            transaction
        });
        
        
        output.schools = await teaching_assignments.getSchools({
            transaction
        });
        
        

        return output;
    }

    static async findAll(
          filter,
           globalAccess,  options
        ) {
        const limit = filter.limit || 0;
        let offset = 0;
        let where = {};
        const currentPage = +filter.page;

        
        const user = (options && options.currentUser) || null;
        const userSchools = (user && user.schools?.id) || null;
        

        
        if (userSchools) {
            if (options?.currentUser?.schoolsId) {
                where.schoolsId = options.currentUser.schoolsId;
            }
        }
        

        offset = currentPage * limit;

        const orderBy = null;

    const transaction = (options && options.transaction) || undefined;

    let include = [

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

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

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

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

      {
        model: db.schools,
        as: 'schools',
        
      },



    ];

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

            

            
            

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

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


      

      

      

      

      
      if (filter.schools) {
        const listItems = filter.schools.split('|').map(item => {
          return  Utils.uuid(item)
        });

        where = {
          ...where,
          schoolsId: {[Op.or]: listItems}
        };
      }
      



            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,
                        },
                    };
                }
            }
        }
        

        
        if (globalAccess) {
            delete where.schoolsId;
        }
        

        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.teaching_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,  globalAccess, organizationId,) {
        let where = {};
        
        
        if (!globalAccess && organizationId) {
            where.organizationId = organizationId;
        }
        

        if (query) {
            where = {
                [Op.or]: [
                    { ['id']: Utils.uuid(query) },
                    Utils.ilike(
                        'teaching_assignments',
                        'assignment_role',
                        query,
                    ),
                ],
            };
        }

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

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

    
};

