import { eq, and } from "drizzle-orm";
import { db } from "../config/database.js";
import {
  homework,
  homeworkSubmissions,
  homeworkAnswers,
  type Homework,
  type NewHomework,
  type HomeworkSubmission,
  type NewHomeworkSubmission,
  type HomeworkAnswer,
  type NewHomeworkAnswer,
} from "./homework.schema.js";

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

  async findByClassId(classId: string): Promise<Homework[]> {
    return db.select().from(homework).where(eq(homework.classId, classId));
  }

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

  async delete(id: string): Promise<void> {
    await db.delete(homework).where(eq(homework.id, id));
  }

  // Submissions
  async findSubmission(
    homeworkId: string,
    studentId: string,
  ): Promise<HomeworkSubmission | undefined> {
    const [result] = await db
      .select()
      .from(homeworkSubmissions)
      .where(
        and(
          eq(homeworkSubmissions.homeworkId, homeworkId),
          eq(homeworkSubmissions.studentId, studentId),
        ),
      )
      .limit(1);
    return result;
  }

  async findSubmissionById(
    id: string,
  ): Promise<HomeworkSubmission | undefined> {
    const [result] = await db
      .select()
      .from(homeworkSubmissions)
      .where(eq(homeworkSubmissions.id, id))
      .limit(1);
    return result;
  }

  async createSubmission(
    submission: NewHomeworkSubmission,
    tx: typeof db = db,
  ): Promise<void> {
    await tx.insert(homeworkSubmissions).values(submission);
  }

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

  // Answers
  async createAnswers(
    answers: NewHomeworkAnswer[],
    tx: typeof db = db,
  ): Promise<void> {
    if (answers.length === 0) return;
    await tx.insert(homeworkAnswers).values(answers);
  }

  async listAnswers(submissionId: string): Promise<HomeworkAnswer[]> {
    return db
      .select()
      .from(homeworkAnswers)
      .where(eq(homeworkAnswers.submissionId, submissionId));
  }
}

export const homeworkRepository = new HomeworkRepository();
