import {
  Body,
  Controller,
  Delete,
  Get,
  Param,
  Post,
  Put,
  Query,
} from "@nestjs/common";
import { TextbooksService } from "./textbooks.service.js";
import type { Textbook } from "./textbooks.schema.js";
import {
  Permissions,
  RequirePermission,
} from "../middleware/permission.guard.js";
import {
  createTextbookSchema,
  updateTextbookSchema,
  listTextbooksSchema,
} from "./textbooks.dto.js";

@Controller("textbooks")
export class TextbooksController {
  constructor(private readonly service: TextbooksService) {}

  @Post()
  @RequirePermission(Permissions.CONTENT_TEXTBOOK_CREATE)
  async create(
    @Body() body: unknown,
  ): Promise<{ success: true; data: { id: string } }> {
    const input = createTextbookSchema.parse(body);
    const result = await this.service.create(input);
    return { success: true, data: result };
  }

  @Get()
  @RequirePermission(Permissions.CONTENT_TEXTBOOK_READ)
  async list(
    @Query() query: unknown,
  ): Promise<{ success: true; data: Textbook[] }> {
    const input = listTextbooksSchema.parse(query);
    const data = await this.service.list(input);
    return { success: true, data };
  }

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

  @Put(":id")
  @RequirePermission(Permissions.CONTENT_TEXTBOOK_UPDATE)
  async update(
    @Param("id") id: string,
    @Body() body: unknown,
  ): Promise<{ success: true; data: { success: true } }> {
    const input = updateTextbookSchema.parse(body);
    await this.service.update(id, input);
    return { success: true, data: { success: true } };
  }

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