import { eq, and } from "drizzle-orm"; import { getDb } from "../config/database.js"; import { electiveCourses, electiveSelections, type ElectiveCourse, type NewElectiveCourse, type ElectiveSelection, type NewElectiveSelection, } from "./electives.schema.js"; export class ElectivesRepository { async findCourseById(id: string): Promise { const [result] = await getDb() .select() .from(electiveCourses) .where(eq(electiveCourses.id, id)) .limit(1); return result; } async findCourses(query?: { subjectId?: string; page?: number; pageSize?: number; }): Promise { const db = getDb(); let q = db.select().from(electiveCourses).$dynamic(); if (query?.subjectId) { q = q.where(eq(electiveCourses.subjectId, query.subjectId)); } const pageSize = query?.pageSize ?? 20; const page = query?.page ?? 1; return q.limit(pageSize).offset((page - 1) * pageSize); } async createCourse(data: NewElectiveCourse): Promise { await getDb().insert(electiveCourses).values(data); } async updateCourse( id: string, data: Partial, ): Promise { await getDb() .update(electiveCourses) .set(data) .where(eq(electiveCourses.id, id)); } async deleteCourse(id: string): Promise { await getDb().delete(electiveCourses).where(eq(electiveCourses.id, id)); } async findSelectionsByStudent( studentId: string, status?: string, ): Promise { const db = getDb(); let q = db .select() .from(electiveSelections) .where(eq(electiveSelections.studentId, studentId)) .$dynamic(); if (status) { q = q.where(eq(electiveSelections.status, status)); } return q; } async findActiveSelection( studentId: string, courseId: string, ): Promise { const [result] = await getDb() .select() .from(electiveSelections) .where( and( eq(electiveSelections.studentId, studentId), eq(electiveSelections.courseId, courseId), eq(electiveSelections.status, "selected"), ), ) .limit(1); return result; } async createSelection(data: NewElectiveSelection): Promise { await getDb().insert(electiveSelections).values(data); } async updateSelection( id: string, data: Partial, ): Promise { await getDb() .update(electiveSelections) .set(data) .where(eq(electiveSelections.id, id)); } async countEnrolled(courseId: string): Promise { const db = getDb(); const rows = await db .select() .from(electiveSelections) .where( and( eq(electiveSelections.courseId, courseId), eq(electiveSelections.status, "selected"), ), ); return rows.length; } } export const electivesRepository = new ElectivesRepository();