import { Body, Controller, Get, Param, Post, Req } from "@nestjs/common";
import {
  HomeworkService,
  type AssignHomeworkInput,
} from "./homework.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("homework")
export class HomeworkController {
  constructor(private readonly homeworkService: HomeworkService) {}

  @Post()
  @RequirePermission(Permissions.HOMEWORK_CREATE)
  async assign(
    @Body() body: AssignHomeworkInput,
    @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.homeworkService.assignHomework({
      ...body,
      createdBy: userId,
    });
    return { success: true, data: result };
  }

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

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

  @Post(":id/submit")
  @RequirePermission(Permissions.HOMEWORK_SUBMIT)
  async submit(
    @Param("id") id: string,
  ): Promise<{ success: true; data: { success: true } }> {
    await this.homeworkService.submitHomework(id);
    return { success: true, data: { success: true } };
  }
}
