import { Body, Controller, Get, Param, Post } from "@nestjs/common";
import { z } from "zod";
import { ClassesService } from "./classes.service.js";
import {
  Permissions,
  RequirePermission,
} from "../middleware/permission.guard.js";
import { ValidationError } from "../shared/errors/application-error.js";

const batchGetSchema = z.object({
  ids: z.array(z.string().min(1)).min(1),
});

@Controller("v1/classes")
export class ClassesController {
  constructor(private readonly classesService: ClassesService) {}

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

  @Get("teacher/:teacherId")
  @RequirePermission(Permissions.CLASS_READ)
  async listByTeacher(@Param("teacherId") teacherId: string): Promise<{
    success: true;
    data: Awaited<ReturnType<ClassesService["getClassesByTeacher"]>>;
  }> {
    const data = await this.classesService.getClassesByTeacher(teacherId);
    return { success: true, data };
  }

  @Post("batch")
  @RequirePermission(Permissions.CLASS_READ)
  async batchGet(@Body() body: unknown): Promise<{
    success: true;
    data: Awaited<ReturnType<ClassesService["batchGetClasses"]>>;
  }> {
    const parsed = batchGetSchema.safeParse(body);
    if (!parsed.success) {
      throw new ValidationError(
        "Invalid batch request",
        parsed.error.flatten(),
      );
    }
    const data = await this.classesService.batchGetClasses(parsed.data.ids);
    return { success: true, data };
  }

  @Get(":classId/students")
  @RequirePermission(Permissions.CLASS_READ)
  async listStudents(@Param("classId") classId: string): Promise<{
    success: true;
    data: Awaited<ReturnType<ClassesService["listStudentsByClass"]>>;
  }> {
    const data = await this.classesService.listStudentsByClass(classId);
    return { success: true, data };
  }
}
