import { Body, Controller, Get, Param, Post, Req } from "@nestjs/common";
import { GradesService, type RecordGradeInput } from "./grades.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("grades")
export class GradesController {
  constructor(private readonly gradesService: GradesService) {}

  @Post()
  @RequirePermission(Permissions.GRADE_CREATE)
  async record(
    @Body() body: RecordGradeInput,
    @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.gradesService.recordGrade({
      ...body,
      gradedBy: userId,
    });
    return { success: true, data: result };
  }

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

  @Get("student/:studentId")
  @RequirePermission(Permissions.GRADE_READ)
  async listByStudent(@Param("studentId") studentId: string): Promise<{
    success: true;
    data: Awaited<ReturnType<GradesService["listByStudent"]>>;
  }> {
    const data = await this.gradesService.listByStudent(studentId);
    return { success: true, data };
  }

  @Get("exam/:examId")
  @RequirePermission(Permissions.GRADE_READ)
  async listByExam(@Param("examId") examId: string): Promise<{
    success: true;
    data: Awaited<ReturnType<GradesService["listByExam"]>>;
  }> {
    const data = await this.gradesService.listByExam(examId);
    return { success: true, data };
  }

  @Get("homework/:homeworkId")
  @RequirePermission(Permissions.GRADE_READ)
  async listByHomework(@Param("homeworkId") homeworkId: string): Promise<{
    success: true;
    data: Awaited<ReturnType<GradesService["listByHomework"]>>;
  }> {
    const data = await this.gradesService.listByHomework(homeworkId);
    return { success: true, data };
  }
}
