import { Body, Controller, Get, Param, Post, Req } from "@nestjs/common";
import { z } from "zod";
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,
  ValidationError,
} from "../shared/errors/application-error.js";

const assignHomeworkSchema = z.object({
  classId: z.string().min(1),
  subjectId: z.string().min(1),
  title: z.string().min(1).max(200),
  description: z.string().optional(),
  dueDate: z.string().min(1),
  gracePeriod: z.number().int().positive().optional(),
  schoolId: z.string().min(1),
});

const answerInputSchema = z.object({
  questionId: z.string().min(1),
  answer: z.string(),
});

const scoreInputSchema = z.object({
  questionId: z.string().min(1),
  score: z.string().min(1),
  teacherComment: z.string().optional(),
});

const submitHomeworkSchema = z.object({
  studentId: z.string().min(1),
  answers: z.array(answerInputSchema).default([]),
});

const gradeHomeworkSchema = z.object({
  submissionId: z.string().min(1),
  scores: z.array(scoreInputSchema).min(1),
  feedback: z.string().optional(),
});

@Controller("v1/homework")
export class HomeworkController {
  constructor(private readonly homeworkService: HomeworkService) {}

  @Post()
  @RequirePermission(Permissions.HOMEWORK_CREATE)
  async assign(
    @Body() body: unknown,
    @Req() req: AuthenticatedRequest,
  ): Promise<{ success: true; data: { id: string } }> {
    const userId = req.userId;
    if (!userId) {
      throw new UnauthorizedError("Missing x-user-id header");
    }
    const parsed = assignHomeworkSchema.safeParse(body);
    if (!parsed.success) {
      throw new ValidationError(
        "Invalid homework input",
        parsed.error.flatten(),
      );
    }
    const input: AssignHomeworkInput = {
      ...parsed.data,
      dueDate: new Date(parsed.data.dueDate),
      createdBy: userId,
    };
    const result = await this.homeworkService.assignHomework(input, 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,
    @Body() body: unknown,
  ): Promise<{ success: true; data: { submissionId: string } }> {
    const parsed = submitHomeworkSchema.safeParse(body);
    if (!parsed.success) {
      throw new ValidationError("Invalid submit input", parsed.error.flatten());
    }
    const result = await this.homeworkService.submitHomework(
      id,
      parsed.data.studentId,
      parsed.data.answers,
    );
    return { success: true, data: result };
  }

  @Post(":id/grade")
  @RequirePermission(Permissions.HOMEWORK_GRADE)
  async grade(
    @Param("id") id: string,
    @Body() body: unknown,
    @Req() req: AuthenticatedRequest,
  ): Promise<{ success: true; data: { totalScore: string } }> {
    const userId = req.userId;
    if (!userId) {
      throw new UnauthorizedError("Missing x-user-id header");
    }
    const parsed = gradeHomeworkSchema.safeParse(body);
    if (!parsed.success) {
      throw new ValidationError("Invalid grade input", parsed.error.flatten());
    }
    const result = await this.homeworkService.gradeHomework(
      id,
      parsed.data.submissionId,
      parsed.data.scores,
      parsed.data.feedback,
      userId,
    );
    return { success: true, data: result };
  }
}
