import {
  Body,
  Controller,
  Delete,
  Get,
  Param,
  Post,
  Put,
} from "@nestjs/common";
import {
  ChaptersService,
  type CreateChapterInput,
  type UpdateChapterInput,
} from "./chapters.service.js";
import type { Chapter } from "./chapters.schema.js";
import {
  Permissions,
  RequirePermission,
} from "../middleware/permission.guard.js";

@Controller("chapters")
export class ChaptersController {
  constructor(private readonly service: ChaptersService) {}

  @Post()
  @RequirePermission(Permissions.CONTENT_CHAPTER_CREATE)
  async create(
    @Body() body: CreateChapterInput,
  ): Promise<{ success: true; data: { id: string } }> {
    const result = await this.service.createChapter(body);
    return { success: true, data: result };
  }

  @Get("textbook/:textbookId")
  @RequirePermission(Permissions.CONTENT_CHAPTER_READ)
  async listByTextbook(
    @Param("textbookId") textbookId: string,
  ): Promise<{ success: true; data: Chapter[] }> {
    const data = await this.service.listChaptersByTextbook(textbookId);
    return { success: true, data };
  }

  @Get(":id")
  @RequirePermission(Permissions.CONTENT_CHAPTER_READ)
  async getById(
    @Param("id") id: string,
  ): Promise<{ success: true; data: Chapter }> {
    const data = await this.service.getChapter(id);
    return { success: true, data };
  }

  @Put(":id")
  @RequirePermission(Permissions.CONTENT_CHAPTER_UPDATE)
  async update(
    @Param("id") id: string,
    @Body() body: UpdateChapterInput,
  ): Promise<{ success: true; data: { success: true } }> {
    await this.service.updateChapter(id, body);
    return { success: true, data: { success: true } };
  }

  @Delete(":id")
  @RequirePermission(Permissions.CONTENT_CHAPTER_DELETE)
  async remove(
    @Param("id") id: string,
  ): Promise<{ success: true; data: { success: true } }> {
    await this.service.deleteChapter(id);
    return { success: true, data: { success: true } };
  }
}
