import { eq } from "drizzle-orm";
import { getDb } from "../config/database.js";
import {
  textbooks,
  type Textbook,
  type NewTextbook,
} from "./textbooks.schema.js";

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

  async find(query?: {
    subjectId?: string;
    gradeId?: string;
    page?: number;
    pageSize?: number;
  }): Promise<Textbook[]> {
    const db = getDb();
    let q = db.select().from(textbooks).$dynamic();
    if (query?.subjectId) {
      q = q.where(eq(textbooks.subjectId, query.subjectId));
    }
    if (query?.gradeId) {
      q = q.where(eq(textbooks.gradeId, query.gradeId));
    }
    const pageSize = query?.pageSize ?? 20;
    const page = query?.page ?? 1;
    return q.limit(pageSize).offset((page - 1) * pageSize);
  }

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

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

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

export const textbooksRepository = new TextbooksRepository();
