import { eq } from "drizzle-orm";
import { db } from "../config/database.js";
import {
  grades,
  gradeFormulas,
  type Grade,
  type NewGrade,
  type GradeFormula,
} from "./grades.schema.js";

export class GradesRepository {
  async findById(id: string): Promise<Grade | undefined> {
    const [result] = await db
      .select()
      .from(grades)
      .where(eq(grades.id, id))
      .limit(1);
    return result;
  }

  async findByStudentId(studentId: string): Promise<Grade[]> {
    return db.select().from(grades).where(eq(grades.studentId, studentId));
  }

  async findByExamId(examId: string): Promise<Grade[]> {
    return db.select().from(grades).where(eq(grades.examId, examId));
  }

  async findByHomeworkId(homeworkId: string): Promise<Grade[]> {
    return db.select().from(grades).where(eq(grades.homeworkId, homeworkId));
  }

  async findByIdempotencyKey(
    idempotencyKey: string,
  ): Promise<Grade | undefined> {
    const [result] = await db
      .select()
      .from(grades)
      .where(eq(grades.idempotencyKey, idempotencyKey))
      .limit(1);
    return result;
  }

  async create(grade: NewGrade, tx: typeof db = db): Promise<void> {
    await tx.insert(grades).values(grade);
  }

  async update(id: string, data: Partial<NewGrade>): Promise<void> {
    await db.update(grades).set(data).where(eq(grades.id, id));
  }

  // Grade formulas
  async findFormulasByScope(
    scope: string,
    _scopeId: string,
  ): Promise<GradeFormula[]> {
    return db
      .select()
      .from(gradeFormulas)
      .where(eq(gradeFormulas.scope, scope));
  }
}

export const gradesRepository = new GradesRepository();
