import {
  Body,
  Controller,
  Delete,
  Get,
  Param,
  Post,
  Put,
} from "@nestjs/common";
import {
  KnowledgePointsService,
  type CreateKnowledgePointInput,
  type UpdateKnowledgePointInput,
  type PrerequisiteNode,
} from "./knowledge-points.service.js";
import type { KnowledgePoint } from "./knowledge-points.schema.js";
import {
  Permissions,
  RequirePermission,
} from "../middleware/permission.guard.js";

@Controller("knowledge-points")
export class KnowledgePointsController {
  constructor(private readonly service: KnowledgePointsService) {}

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

  @Get("chapter/:chapterId")
  @RequirePermission(Permissions.CONTENT_KNOWLEDGE_POINT_READ)
  async listByChapter(
    @Param("chapterId") chapterId: string,
  ): Promise<{ success: true; data: KnowledgePoint[] }> {
    const data = await this.service.listByChapter(chapterId);
    return { success: true, data };
  }

  @Get(":id/prerequisites")
  @RequirePermission(Permissions.CONTENT_KNOWLEDGE_POINT_READ)
  async getPrerequisites(
    @Param("id") id: string,
  ): Promise<{ success: true; data: PrerequisiteNode[] }> {
    const data = await this.service.getPrerequisites(id);
    return { success: true, data };
  }

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

  @Post(":id/prerequisites/:prerequisiteId")
  @RequirePermission(Permissions.CONTENT_KNOWLEDGE_POINT_UPDATE)
  async addPrerequisite(
    @Param("id") id: string,
    @Param("prerequisiteId") prerequisiteId: string,
  ): Promise<{ success: true; data: { success: true } }> {
    await this.service.addPrerequisite(id, prerequisiteId);
    return { success: true, data: { success: true } };
  }

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

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