import {
  Body,
  Controller,
  Delete,
  Get,
  Param,
  Post,
  Put,
  Req,
} from "@nestjs/common";
import {
  ExamsService,
  type CreateExamInput,
  type UpdateExamInput,
} from "./exams.service.js";
import {
  Permissions,
  RequirePermission,
} from "../middleware/permission.guard.js";
import type { AuthenticatedRequest } from "../middleware/auth.middleware.js";
import { UnauthorizedError } from "../shared/errors/application-error.js";

@Controller("exams")
export class ExamsController {
  constructor(private readonly examsService: ExamsService) {}

  @Post()
  @RequirePermission(Permissions.EXAM_CREATE)
  async create(
    @Body() body: CreateExamInput,
    @Req() req: AuthenticatedRequest,
  ): Promise<{ success: true; data: { id: string } }> {
    const userId = req.userId;
    if (!userId) {
      throw new UnauthorizedError("Missing x-user-id header");
    }
    const result = await this.examsService.createExam({
      ...body,
      createdBy: userId,
    });
    return { success: true, data: result };
  }

  @Get(":id")
  @RequirePermission(Permissions.EXAM_READ)
  async findOne(@Param("id") id: string): Promise<{
    success: true;
    data: Awaited<ReturnType<ExamsService["getExam"]>>;
  }> {
    const data = await this.examsService.getExam(id);
    return { success: true, data };
  }

  @Get("class/:classId")
  @RequirePermission(Permissions.EXAM_READ)
  async listByClass(@Param("classId") classId: string): Promise<{
    success: true;
    data: Awaited<ReturnType<ExamsService["listExamsByClass"]>>;
  }> {
    const data = await this.examsService.listExamsByClass(classId);
    return { success: true, data };
  }

  @Put(":id")
  @RequirePermission(Permissions.EXAM_UPDATE)
  async update(
    @Param("id") id: string,
    @Body() body: UpdateExamInput,
  ): Promise<{ success: true; data: { success: true } }> {
    await this.examsService.updateExam(id, body);
    return { success: true, data: { success: true } };
  }

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