import { Controller, Get, Param, Req } from "@nestjs/common";
import type { Request } from "express";
import { TeacherService } from "./teacher.service.js";
import { UnauthorizedError } from "../shared/errors/application-error.js";

interface SuccessResponse<T> {
  success: true;
  data: T;
}

@Controller("teacher")
export class TeacherController {
  constructor(private readonly service: TeacherService) {}

  @Get("dashboard")
  async dashboard(@Req() req: Request): Promise<SuccessResponse<unknown>> {
    const userId = this.extractUserId(req);
    const data = await this.service.getDashboard(userId);
    return { success: true as const, data };
  }

  @Get("viewports")
  async viewports(@Req() req: Request): Promise<SuccessResponse<unknown>> {
    const userId = this.extractUserId(req);
    const data = await this.service.getViewports(userId);
    return { success: true as const, data };
  }

  // 聚合：班级下的考试列表（core-edu）
  @Get("classes/:classId/exams")
  async listExamsByClass(
    @Req() req: Request,
    @Param("classId") classId: string,
  ): Promise<SuccessResponse<unknown>> {
    const userId = this.extractUserId(req);
    const data = await this.service.listExamsByClass(userId, classId);
    return { success: true as const, data };
  }

  // 聚合：班级下的作业列表（core-edu）
  @Get("classes/:classId/homework")
  async listHomeworkByClass(
    @Req() req: Request,
    @Param("classId") classId: string,
  ): Promise<SuccessResponse<unknown>> {
    const userId = this.extractUserId(req);
    const data = await this.service.listHomeworkByClass(userId, classId);
    return { success: true as const, data };
  }

  // 聚合：考试下的成绩列表（core-edu）
  @Get("exams/:examId/grades")
  async listGradesByExam(
    @Req() req: Request,
    @Param("examId") examId: string,
  ): Promise<SuccessResponse<unknown>> {
    const userId = this.extractUserId(req);
    const data = await this.service.listGradesByExam(userId, examId);
    return { success: true as const, data };
  }

  private extractUserId(req: Request): string {
    const header = req.headers["x-user-id"];
    const userId = typeof header === "string" ? header : undefined;
    if (!userId) {
      throw new UnauthorizedError("Missing x-user-id header");
    }
    return userId;
  }
}
