import { randomUUID } from "node:crypto";
import { Injectable } from "@nestjs/common";
import { chaptersRepository } from "./chapters.repository.js";
import type { Chapter } from "./chapters.schema.js";
import {
  NotFoundError,
  ValidationError,
} from "../shared/errors/application-error.js";

export interface CreateChapterInput {
  textbookId: string;
  title: string;
  order: number;
  parentId?: string;
}

export interface UpdateChapterInput {
  title?: string;
  order?: number;
  parentId?: string;
}

@Injectable()
export class ChaptersService {
  async createChapter(input: CreateChapterInput): Promise<{ id: string }> {
    if (!input.textbookId || !input.title || input.order === undefined) {
      throw new ValidationError("textbookId, title, order are required");
    }

    const id = randomUUID();
    await chaptersRepository.create({
      id,
      textbookId: input.textbookId,
      title: input.title,
      order: input.order,
      parentId: input.parentId,
    });
    return { id };
  }

  async getChapter(id: string): Promise<Chapter> {
    const chapter = await chaptersRepository.findById(id);
    if (!chapter) {
      throw new NotFoundError("Chapter", id);
    }
    return chapter;
  }

  async listChaptersByTextbook(textbookId: string): Promise<Chapter[]> {
    return chaptersRepository.findByTextbookId(textbookId);
  }

  async updateChapter(id: string, data: UpdateChapterInput): Promise<void> {
    await this.getChapter(id);
    await chaptersRepository.update(id, data);
  }

  async deleteChapter(id: string): Promise<void> {
    await this.getChapter(id);
    await chaptersRepository.delete(id);
  }
}
