import { eq } from "drizzle-orm";
import { getDb } from "../config/database.js";
import {
  knowledgePoints,
  type KnowledgePoint,
  type NewKnowledgePoint,
} from "./knowledge-points.schema.js";

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

  async findByChapterId(chapterId: string): Promise<KnowledgePoint[]> {
    return getDb()
      .select()
      .from(knowledgePoints)
      .where(eq(knowledgePoints.chapterId, chapterId));
  }

  async create(data: NewKnowledgePoint): Promise<void> {
    await getDb().insert(knowledgePoints).values(data);
  }

  async update(id: string, data: Partial<NewKnowledgePoint>): Promise<void> {
    await getDb()
      .update(knowledgePoints)
      .set(data)
      .where(eq(knowledgePoints.id, id));
  }

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

export const knowledgePointsRepository = new KnowledgePointsRepository();
