import {
  Body,
  Controller,
  Delete,
  Get,
  Param,
  Post,
  Put,
  Query,
} from "@nestjs/common";
import { QuestionsService } from "./questions.service.js";
import type { Question } from "./questions.schema.js";
import {
  Permissions,
  RequirePermission,
} from "../middleware/permission.guard.js";
import {
  createQuestionSchema,
  updateQuestionSchema,
  listQuestionsSchema,
} from "./questions.dto.js";

@Controller("questions")
export class QuestionsController {
  constructor(private readonly service: QuestionsService) {}

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

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

  @Get("knowledge-point/:knowledgePointId")
  @RequirePermission(Permissions.CONTENT_QUESTION_READ)
  async listByKnowledgePoint(
    @Param("knowledgePointId") knowledgePointId: string,
  ): Promise<{ success: true; data: Question[] }> {
    const data = await this.service.listByKnowledgePoint(knowledgePointId);
    return { success: true, data };
  }

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

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

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