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

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

        const classroom_memberships = await db.classroom_memberships.create(
            {
                id: data.id || undefined,
        
        joined_at: data.joined_at
        ||
        null
            ,
            
        membership_status: data.membership_status
        ||
        null
            ,
            
        join_method: data.join_method
        ||
        null
            ,
            
        notes: data.notes
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        
        await classroom_memberships.setClassroom( data.classroom || null, {
            transaction,
        });
        
        await classroom_memberships.setStudent( data.student || null, {
            transaction,
        });
        
        await classroom_memberships.setSchools( data.schools || null, {
            transaction,
        });
        

        

        

        return classroom_memberships;
    }
    

    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 classroom_membershipsData = data.map((item, index) => ({
                id: item.id || undefined,
                
                joined_at: item.joined_at
            ||
            null
            ,
            
                membership_status: item.membership_status
            ||
            null
            ,
            
                join_method: item.join_method
            ||
            null
            ,
            
                notes: item.notes
            ||
            null
            ,
            
            importHash: item.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
            createdAt: new Date(Date.now() + index * 1000),
    }));

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

        // For each item created, replace relation files
        

        return classroom_memberships;
    }

    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 classroom_memberships = await db.classroom_memberships.findByPk(id, {}, {transaction});


        

        const updatePayload = {};
        
        if (data.joined_at !== undefined) updatePayload.joined_at = data.joined_at;
        
        
        if (data.membership_status !== undefined) updatePayload.membership_status = data.membership_status;
        
        
        if (data.join_method !== undefined) updatePayload.join_method = data.join_method;
        
        
        if (data.notes !== undefined) updatePayload.notes = data.notes;
        
        
        updatePayload.updatedById = currentUser.id;

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

        
        
        if (data.classroom !== undefined) {
            await classroom_memberships.setClassroom(
              
              data.classroom,
              
              { transaction }
            );
        }
        
        if (data.student !== undefined) {
            await classroom_memberships.setStudent(
              
              data.student,
              
              { transaction }
            );
        }
        
        if (data.schools !== undefined) {
            await classroom_memberships.setSchools(
              
              data.schools,
              
              { transaction }
            );
        }
        

        
        

        

        return classroom_memberships;
    }

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

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

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


        return classroom_memberships;
    }

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

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

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

        await classroom_memberships.destroy({
            transaction
        });

        return classroom_memberships;
    }

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

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

        if (!classroom_memberships) {
            return classroom_memberships;
        }

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

        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        
        output.classroom = await classroom_memberships.getClassroom({
            transaction
        });
        
        
        output.student = await classroom_memberships.getStudent({
            transaction
        });
        
        
        output.schools = await classroom_memberships.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.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.users,
        as: 'student',
        
        where: filter.student ? {
          [Op.or]: [
            { id: { [Op.in]: filter.student.split('|').map(term => Utils.uuid(term)) } },
            {
              firstName: {
                [Op.or]: filter.student.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.join_method) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'classroom_memberships',
                        'join_method',
                        filter.join_method,
                    ),
                };
            }
            
            if (filter.notes) {
                where = {
                    ...where,
                    [Op.and]: Utils.ilike(
                        'classroom_memberships',
                        'notes',
                        filter.notes,
                    ),
                };
            }
            

            
            

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

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

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

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

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


      

      

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

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

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

    
};

