import { randomUUID } from "node:crypto";
import { eq } from "drizzle-orm";
import { Injectable } from "@nestjs/common";
import { db } from "../config/database.js";
import { textbooks, type Textbook } from "./textbooks.schema.js";
import {
  NotFoundError,
  ValidationError,
} from "../shared/errors/application-error.js";

export interface CreateTextbookInput {
  title: string;
  subjectId: string;
  gradeId: string;
  version: string;
}

export interface UpdateTextbookInput {
  title?: string;
  subjectId?: string;
  gradeId?: string;
  version?: string;
}

@Injectable()
export class TextbooksService {
  async create(input: CreateTextbookInput): Promise<{ id: string }> {
    if (!input.title || !input.subjectId || !input.gradeId || !input.version) {
      throw new ValidationError(
        "title, subjectId, gradeId, version are required",
      );
    }

    const id = randomUUID();
    await db.insert(textbooks).values({
      id,
      title: input.title,
      subjectId: input.subjectId,
      gradeId: input.gradeId,
      version: input.version,
    });
    return { id };
  }

  async list(): Promise<Textbook[]> {
    return db.select().from(textbooks);
  }

  async getById(id: string): Promise<Textbook> {
    const [result] = await db
      .select()
      .from(textbooks)
      .where(eq(textbooks.id, id))
      .limit(1);
    if (!result) {
      throw new NotFoundError("Textbook", id);
    }
    return result;
  }

  async update(id: string, data: UpdateTextbookInput): Promise<void> {
    await this.getById(id);
    await db.update(textbooks).set(data).where(eq(textbooks.id, id));
  }

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