import { z } from "zod"

/**
 * Zod 校验错误消息使用 i18n 键（参考 `auth/schema.ts` 模式）。
 *
 * Server Action 在校验失败时调用 `getTranslations("examHomework")` 翻译这些键
 * 后再返回 `fieldErrors`。键定义于 `messages/{locale}/exam-homework.json`
 * 的 `homework.form.error.*` 命名空间下。
 */
const dateStringSchema = z
  .string()
  .refine((v) => !Number.isNaN(new Date(v).getTime()), "homework.form.error.invalidDate")

export const CreateHomeworkAssignmentSchema = z
  .object({
    sourceExamId: z.string().optional(),
    classId: z.string().min(1),
    title: z.string().min(1, "homework.form.error.titleRequired"),
    description: z.string().optional(),
    availableAt: dateStringSchema.optional(),
    dueAt: dateStringSchema.optional(),
    allowLate: z.coerce.boolean().optional(),
    lateDueAt: dateStringSchema.optional(),
    maxAttempts: z.coerce.number().int().min(1).max(20).optional(),
    targetStudentIds: z.array(z.string().min(1)).optional(),
    publish: z.coerce.boolean().optional(),
  })
  .superRefine((data, ctx) => {
    // 时序校验：availableAt < dueAt < lateDueAt
    const available = data.availableAt ? new Date(data.availableAt).getTime() : null
    const due = data.dueAt ? new Date(data.dueAt).getTime() : null
    const lateDue = data.lateDueAt ? new Date(data.lateDueAt).getTime() : null

    if (available !== null && due !== null && available > due) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        path: ["dueAt"],
        message: "homework.form.error.dueAfterAvailable",
      })
    }
    if (due !== null && lateDue !== null && due > lateDue) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        path: ["lateDueAt"],
        message: "homework.form.error.lateDueAfterDue",
      })
    }
    if (data.allowLate && !data.lateDueAt) {
      ctx.addIssue({
        code: z.ZodIssueCode.custom,
        path: ["lateDueAt"],
        message: "homework.form.error.lateDueRequired",
      })
    }
  })

export type CreateHomeworkAssignmentInput = z.infer<typeof CreateHomeworkAssignmentSchema>

export const GradeHomeworkSchema = z.object({
  submissionId: z.string().min(1),
  answers: z.array(
    z.object({
      id: z.string().min(1),
      score: z.coerce.number().min(0),
      feedback: z.string().optional(),
    })
  ),
})
