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

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

        const schools = await db.schools.create(
            {
                id: data.id || undefined,
        
        name: data.name
        ||
        null
            ,
            
            importHash: data.importHash || null,
            createdById: currentUser.id,
            updatedById: currentUser.id,
    },
        { transaction },
    );

        

        

        

        return schools;
    }
    

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

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

        // For each item created, replace relation files
        

        return schools;
    }

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


        

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

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

        
        

        
        

        

        return schools;
    }

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

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

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


        return schools;
    }

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

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

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

        await schools.destroy({
            transaction
        });

        return schools;
    }

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

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

        if (!schools) {
            return schools;
        }

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

        
        output.users_schools = await schools.getUsers_schools({
            transaction
        });
        
        
        
        
        
        output.grade_levels_school = await schools.getGrade_levels_school({
            transaction
        });
        
        
        output.subjects_school = await schools.getSubjects_school({
            transaction
        });
        
        
        output.classrooms_school = await schools.getClassrooms_school({
            transaction
        });
        
        
        output.classroom_memberships_schools = await schools.getClassroom_memberships_schools({
            transaction
        });
        
        
        output.teaching_assignments_schools = await schools.getTeaching_assignments_schools({
            transaction
        });
        
        
        output.homeworks_schools = await schools.getHomeworks_schools({
            transaction
        });
        
        
        output.homework_rubrics_schools = await schools.getHomework_rubrics_schools({
            transaction
        });
        
        
        output.homework_extensions_schools = await schools.getHomework_extensions_schools({
            transaction
        });
        
        
        output.homework_submissions_schools = await schools.getHomework_submissions_schools({
            transaction
        });
        
        
        output.submission_grades_schools = await schools.getSubmission_grades_schools({
            transaction
        });
        
        
        output.rubric_scores_schools = await schools.getRubric_scores_schools({
            transaction
        });
        
        
        output.gradebooks_school = await schools.getGradebooks_school({
            transaction
        });
        
        
        output.gradebook_columns_schools = await schools.getGradebook_columns_schools({
            transaction
        });
        
        
        output.gradebook_entries_schools = await schools.getGradebook_entries_schools({
            transaction
        });
        
        
        output.adviser_reports_schools = await schools.getAdviser_reports_schools({
            transaction
        });
        
        
        output.announcements_school = await schools.getAnnouncements_school({
            transaction
        });
        
        
        output.notifications_schools = await schools.getNotifications_schools({
            transaction
        });
        
        
        output.account_applications_school = await schools.getAccount_applications_school({
            transaction
        });
        
        
        output.guardians_school = await schools.getGuardians_school({
            transaction
        });
        
        
        output.security_events_school = await schools.getSecurity_events_school({
            transaction
        });
        
        
        output.support_settings_schools = await schools.getSupport_settings_schools({
            transaction
        });
        
        
        output.feedback_items_school = await schools.getFeedback_items_school({
            transaction
        });
        
        
        output.events_school = await schools.getEvents_school({
            transaction
        });
        
        
        output.ai_monitoring_rules_schools = await schools.getAi_monitoring_rules_schools({
            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 = [



    ];

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

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

            
            

            

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

            




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

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

    
};

