import { eq } from "drizzle-orm";
import { db } from "../config/database.js";
import { chapters, type Chapter, type NewChapter } from "./chapters.schema.js";

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

  async findByTextbookId(textbookId: string): Promise<Chapter[]> {
    return db
      .select()
      .from(chapters)
      .where(eq(chapters.textbookId, textbookId));
  }

  async create(data: NewChapter): Promise<void> {
    await db.insert(chapters).values(data);
  }

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

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

export const chaptersRepository = new ChaptersRepository();
