import { z } from "zod";

/**
 * Shared Zod schemas.
 *
 * Every mutating server action parses its input through one of these before
 * touching the database, so validation rules live in exactly one place and are
 * reused by both the client (inline feedback) and the server (trust boundary).
 */

// --- primitives -------------------------------------------------------------

export const cuid = z.string().min(1, "Wajib diisi.");

export const usernameSchema = z
  .string()
  .trim()
  .min(3, "Username minimal 3 karakter.")
  .max(32, "Username maksimal 32 karakter.")
  .regex(
    /^[a-zA-Z0-9._-]+$/,
    "Username hanya boleh berisi huruf, angka, titik, garis bawah, dan tanda hubung."
  );

export const passwordSchema = z
  .string()
  .min(8, "Kata sandi minimal 8 karakter.")
  .max(200, "Kata sandi terlalu panjang.")
  .regex(/[A-Za-z]/, "Kata sandi harus mengandung minimal satu huruf.")
  .regex(/[0-9]/, "Kata sandi harus mengandung minimal satu angka.");

export const hexColor = z
  .string()
  .regex(/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/, "Harus berupa warna hex yang valid (mis. #26241c).");

export const optionalUrl = z
  .string()
  .trim()
  .url("Harus berupa URL yang valid.")
  .or(z.literal(""))
  .optional()
  .transform((value) => (value === "" ? undefined : value));

// --- auth -------------------------------------------------------------------

export const loginSchema = z.object({
  username: z.string().trim().min(1, "Username wajib diisi.").max(64),
  password: z.string().min(1, "Kata sandi wajib diisi.").max(200),
  next: z.string().max(2048).optional(),
});

export const registerSchema = z.object({
  username: usernameSchema,
  fullName: z.string().trim().min(2, "Nama lengkap wajib diisi.").max(120),
  email: z.string().trim().email("Masukkan alamat email yang valid.").optional().or(z.literal("")),
  password: passwordSchema,
  role: z.enum(["STUDENT", "TEACHER"]).default("STUDENT"),
  joinCode: z.string().trim().max(16).optional(),
});

export const changePasswordSchema = z
  .object({
    currentPassword: z.string().min(1, "Kata sandi saat ini wajib diisi."),
    newPassword: passwordSchema,
    confirmPassword: z.string().min(1, "Konfirmasi kata sandi baru wajib diisi."),
  })
  .refine((data) => data.newPassword === data.confirmPassword, {
    message: "Kata sandi tidak cocok.",
    path: ["confirmPassword"],
  });

export const profileSchema = z.object({
  fullName: z.string().trim().min(2, "Nama lengkap wajib diisi.").max(120),
  email: z.string().trim().email("Masukkan alamat email yang valid.").optional().or(z.literal("")),
  phone: z.string().trim().max(40).optional().or(z.literal("")),
  school: z.string().trim().max(160).optional().or(z.literal("")),
  gradeLevel: z.string().trim().max(40).optional().or(z.literal("")),
  bio: z.string().trim().max(600, "Bio maksimal 600 karakter.").optional().or(z.literal("")),
  // Rendered as <img src> for other users, so it must be a real, bounded URL.
  // Left unbounded it accepted any string, including data: URIs and oversized
  // values that bloat every page that renders the avatar.
  avatarUrl: z
    .string()
    .trim()
    .max(2048, "URL foto maksimal 2048 karakter.")
    .refine((value) => value === "" || /^https?:\/\//i.test(value), {
      message: "URL foto harus diawali http:// atau https://.",
    })
    .optional()
    .or(z.literal("")),
});

// --- admin user management --------------------------------------------------

export const adminCreateUserSchema = z.object({
  username: usernameSchema,
  fullName: z.string().trim().min(2, "Nama lengkap wajib diisi.").max(120),
  email: z.string().trim().email("Masukkan alamat email yang valid.").optional().or(z.literal("")),
  password: passwordSchema,
  role: z.enum(["ADMIN", "TEACHER", "STUDENT"]),
  status: z.enum(["ACTIVE", "SUSPENDED", "PENDING"]).default("ACTIVE"),
  school: z.string().trim().max(160).optional().or(z.literal("")),
  gradeLevel: z.string().trim().max(40).optional().or(z.literal("")),
});

export const adminUpdateUserSchema = z.object({
  userId: cuid,
  fullName: z.string().trim().min(2, "Nama lengkap wajib diisi.").max(120),
  email: z.string().trim().email("Masukkan alamat email yang valid.").optional().or(z.literal("")),
  role: z.enum(["ADMIN", "TEACHER", "STUDENT"]),
  status: z.enum(["ACTIVE", "SUSPENDED", "PENDING"]),
  school: z.string().trim().max(160).optional().or(z.literal("")),
  gradeLevel: z.string().trim().max(40).optional().or(z.literal("")),
});

export const adminResetPasswordSchema = z.object({
  userId: cuid,
  newPassword: passwordSchema,
});

// --- classroom --------------------------------------------------------------

export const classroomSchema = z.object({
  name: z.string().trim().min(2, "Nama kelas wajib diisi.").max(120),
  description: z.string().trim().max(600).optional().or(z.literal("")),
  academicYear: z.string().trim().min(4, "Tahun ajaran wajib diisi.").max(20),
  gradeLevel: z.string().trim().max(40).optional().or(z.literal("")),
  room: z.string().trim().max(60).optional().or(z.literal("")),
  teacherId: cuid.optional(),
});

export const joinClassSchema = z.object({
  joinCode: z.string().trim().min(4, "Kode kelas wajib diisi.").max(12),
});

// --- course / module / lesson ----------------------------------------------

export const courseSchema = z.object({
  title: z.string().trim().min(3, "Judul kursus wajib diisi.").max(160),
  summary: z.string().trim().max(400).optional().or(z.literal("")),
  description: z.string().trim().max(8000).optional().or(z.literal("")),
  level: z.enum(["BEGINNER", "INTERMEDIATE", "ADVANCED"]).default("BEGINNER"),
  language: z.enum(["JAVASCRIPT", "PYTHON", "ROBOT"]).default("JAVASCRIPT"),
  status: z.enum(["DRAFT", "PUBLISHED", "ARCHIVED"]).default("DRAFT"),
  estimatedHours: z.coerce.number().int().min(1).max(400).default(8),
  coverColor: hexColor.default("#26241c"),
  tags: z.array(z.string().trim().min(1).max(40)).max(12).default([]),
  classroomId: z.string().optional().or(z.literal("")),
});

export const moduleSchema = z.object({
  courseId: cuid,
  title: z.string().trim().min(2, "Judul modul wajib diisi.").max(160),
  description: z.string().trim().max(1000).optional().or(z.literal("")),
  orderIndex: z.coerce.number().int().min(0).default(0),
});

export const lessonSchema = z.object({
  courseId: cuid,
  moduleId: z.string().optional().or(z.literal("")),
  title: z.string().trim().min(3, "Judul pelajaran wajib diisi.").max(200),
  summary: z.string().trim().max(400).optional().or(z.literal("")),
  content: z.string().max(200000).default(""),
  type: z.enum(["TEXT", "VIDEO", "INTERACTIVE", "CODE_LAB", "QUIZ"]).default("TEXT"),
  videoUrl: z.string().trim().optional().or(z.literal("")),
  attachmentUrl: z.string().trim().optional().or(z.literal("")),
  durationMinutes: z.coerce.number().int().min(1).max(600).default(30),
  orderIndex: z.coerce.number().int().min(0).default(0),
  isPreview: z.coerce.boolean().default(false),
  status: z.enum(["DRAFT", "PUBLISHED", "ARCHIVED"]).default("DRAFT"),
  objectives: z.array(z.string().trim().min(1).max(200)).max(20).default([]),
});

// --- attendance -------------------------------------------------------------

export const attendanceSessionSchema = z.object({
  classId: cuid,
  courseId: z.string().optional().or(z.literal("")),
  date: z.coerce.date(),
  topic: z.string().trim().max(200).optional().or(z.literal("")),
  note: z.string().trim().max(600).optional().or(z.literal("")),
});

export const attendanceMarkSchema = z.object({
  sessionId: cuid,
  records: z
    .array(
      z.object({
        studentId: cuid,
        status: z.enum(["PRESENT", "LATE", "ABSENT", "EXCUSED"]),
        note: z.string().trim().max(300).optional().or(z.literal("")),
      })
    )
    .min(1, "No attendance records supplied."),
});

// --- assignments & submissions ---------------------------------------------

export const assignmentSchema = z.object({
  courseId: cuid,
  lessonId: z.string().optional().or(z.literal("")),
  title: z.string().trim().min(3, "Judul tugas wajib diisi.").max(200),
  description: z.string().max(20000).default(""),
  instructions: z.string().max(20000).optional().or(z.literal("")),
  type: z.enum(["HOMEWORK", "PROJECT", "QUIZ", "CODING", "EXAM"]).default("HOMEWORK"),
  maxScore: z.coerce.number().int().min(1).max(1000).default(100),
  weight: z.coerce.number().int().min(1).max(20).default(1),
  dueAt: z.coerce.date().optional(),
  allowLate: z.coerce.boolean().default(true),
  status: z.enum(["DRAFT", "PUBLISHED", "ARCHIVED"]).default("DRAFT"),
});

export const submissionSchema = z.object({
  assignmentId: cuid,
  content: z.string().max(50000).optional().or(z.literal("")),
  // `fileUrl`, `fileName` and `fileSize` are deliberately absent: the server
  // derives them from the uploaded file. Accepting them here let a student
  // choose the storage key their submission was authorized against.
  submit: z.coerce.boolean().default(true),
});

export const gradeSchema = z.object({
  submissionId: cuid,
  score: z.coerce.number().min(0, "Nilai tidak boleh negatif."),
  feedback: z.string().max(10000).optional().or(z.literal("")),
  returnToStudent: z.coerce.boolean().default(true),
});

// --- quiz -------------------------------------------------------------------

export const questionTypeSchema = z.enum([
  "MULTIPLE_CHOICE",
  "MULTI_SELECT",
  "TRUE_FALSE",
  "SHORT_ANSWER",
  "CODE",
]);

/**
 * One question as the authoring form submits it.
 *
 * `correctAnswer` is a union because each type stores a different shape: an
 * index, a list of indices, or free text. Which one is valid depends on `type`,
 * and that pairing is checked in `superRefine` rather than by the field itself.
 */
export const quizQuestionSchema = z
  .object({
    /**
     * Present when the author is editing a question that already exists.
     * Declaring it here rather than casting at the read site keeps the parsed
     * value fully typed.
     */
    id: z.string().min(1).optional(),
    prompt: z.string().trim().min(3, "Tulis pertanyaan.").max(1000),
    type: questionTypeSchema,
    options: z.array(z.string().trim().min(1)).max(10, "Maksimal 10 pilihan.").default([]),
    correctAnswer: z.union([
      z.number().int().min(0),
      z.array(z.number().int().min(0)),
      z.string().trim(),
    ]),
    explanation: z.string().trim().max(1000).optional().or(z.literal("")),
    points: z.coerce.number().int().min(1, "Poin minimal 1.").max(100),
    orderIndex: z.coerce.number().int().min(0).default(0),
  })
  .superRefine((question, ctx) => {
    const { type, options, correctAnswer } = question;

    if (type === "MULTIPLE_CHOICE" || type === "TRUE_FALSE" || type === "MULTI_SELECT") {
      if (options.length < 2) {
        ctx.addIssue({
          code: "custom",
          path: ["options"],
          message: "Sediakan minimal dua pilihan jawaban.",
        });
        return;
      }

      if (type === "MULTI_SELECT") {
        if (!Array.isArray(correctAnswer) || correctAnswer.length === 0) {
          ctx.addIssue({
            code: "custom",
            path: ["correctAnswer"],
            message: "Pilih minimal satu jawaban benar.",
          });
          return;
        }
        if (correctAnswer.some((index) => index >= options.length)) {
          ctx.addIssue({
            code: "custom",
            path: ["correctAnswer"],
            message: "Ada kunci jawaban yang menunjuk pilihan yang tidak ada.",
          });
        }
        return;
      }

      if (typeof correctAnswer !== "number") {
        ctx.addIssue({
          code: "custom",
          path: ["correctAnswer"],
          message: "Pilih satu jawaban benar.",
        });
        return;
      }
      if (correctAnswer >= options.length) {
        ctx.addIssue({
          code: "custom",
          path: ["correctAnswer"],
          message: "Kunci jawaban menunjuk pilihan yang tidak ada.",
        });
      }
      return;
    }

    if (type === "SHORT_ANSWER" && typeof correctAnswer !== "string") {
      ctx.addIssue({
        code: "custom",
        path: ["correctAnswer"],
        message: "Tulis kunci jawaban berupa teks.",
      });
    }
  });

/**
 * Quiz settings attached to a QUIZ assignment.
 *
 * `passingScore` is a percentage, matching `Quiz.passingScore` in the schema.
 */
export const quizSchema = z.object({
  assignmentId: cuid,
  passingScore: z.coerce.number().int().min(0, "Minimal 0.").max(100, "Maksimal 100."),
  timeLimitMinutes: z.coerce.number().int().min(0).max(600, "Batas waktu maksimal 600 menit.").optional(),
  shuffleQuestions: z.boolean().default(false),
  allowRetakes: z.boolean().default(true),
  maxAttempts: z.coerce.number().int().min(1, "Minimal satu percobaan.").max(20, "Maksimal 20 percobaan."),
  questions: z.array(quizQuestionSchema).min(1, "Tambahkan minimal satu soal.").max(100, "Maksimal 100 soal."),
});

/**
 * A student's submission of one attempt.
 *
 * Answers arrive as a JSON string in a single field rather than as many
 * dynamically named fields: the question set is only known at runtime, and one
 * encoded payload keeps the form's shape stable across question types.
 */
export const quizAnswerSchema = z.object({
  attemptId: cuid,
  answers: z.string().transform((raw, ctx) => {
    try {
      const parsed: unknown = JSON.parse(raw);
      if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
        ctx.addIssue({ code: "custom", message: "Format jawaban tidak dikenali." });
        return z.NEVER;
      }
      return parsed as Record<string, unknown>;
    } catch {
      ctx.addIssue({ code: "custom", message: "Format jawaban tidak dikenali." });
      return z.NEVER;
    }
  }),
});

// --- coding -----------------------------------------------------------------

export const codingProjectSchema = z.object({
  title: z.string().trim().min(3, "Judul proyek wajib diisi.").max(200),
  description: z.string().max(20000).default(""),
  brief: z.string().max(20000).optional().or(z.literal("")),
  language: z.enum(["JAVASCRIPT", "PYTHON", "ROBOT"]).default("JAVASCRIPT"),
  difficulty: z.enum(["BEGINNER", "INTERMEDIATE", "ADVANCED"]).default("BEGINNER"),
  starterCode: z.string().max(50000).default(""),
  solutionCode: z.string().max(50000).optional().or(z.literal("")),
  hints: z.array(z.string().trim().max(400)).max(10).default([]),
  xpReward: z.coerce.number().int().min(0).max(1000).default(50),
  status: z.enum(["DRAFT", "PUBLISHED", "ARCHIVED"]).default("DRAFT"),
  courseId: z.string().optional().or(z.literal("")),
  skillIds: z.array(cuid).max(8).default([]),
});

export const codingRunSchema = z.object({
  projectId: cuid,
  code: z.string().min(1, "Write some code first.").max(100000),
});

// --- simulator --------------------------------------------------------------

export const simulatorRunSchema = z.object({
  challengeId: cuid,
  program: z.string().min(1, "Write a program first.").max(50000),
});

// --- announcements ----------------------------------------------------------

export const announcementSchema = z.object({
  title: z.string().trim().min(3, "Judul wajib diisi.").max(200),
  body: z.string().trim().min(3, "Isi pengumuman wajib diisi.").max(20000),
  classId: z.string().optional().or(z.literal("")),
  courseId: z.string().optional().or(z.literal("")),
  pinned: z.coerce.boolean().default(false),
});

export const knowledgeEntrySchema = z.object({
  topic: z.string().trim().min(3, "Topik wajib diisi.").max(120),
  // Free text, one phrase per line — the admin should not have to write JSON.
  keywords: z
    .string()
    .transform((raw) =>
      raw
        .split(/[\n,]/)
        .map((k) => k.trim().toLowerCase())
        .filter((k) => k.length >= 2)
    )
    .pipe(
      z
        .array(z.string())
        .min(1, "Isi minimal satu kata kunci, satu per baris.")
        .max(40, "Maksimal 40 kata kunci.")
    ),
  answer: z.string().trim().min(10, "Jawaban wajib diisi.").max(4000),
  priority: z.coerce.number().int().min(0).max(9).default(0),
  // Callers pass a real boolean: an unchecked HTML checkbox submits nothing,
  // so coercing the raw FormData value would read every unchecked box as true.
  published: z.boolean().default(true),
});

// --- certificates -----------------------------------------------------------

export const certificateIssueSchema = z.object({
  studentId: cuid,
  courseId: cuid,
});

export const certificateRevokeSchema = z.object({
  certificateId: cuid,
  note: z.string().trim().max(300, "Catatan maksimal 300 karakter.").optional().or(z.literal("")),
});

export const certificateVerifySchema = z.object({
  serial: z.string().trim().min(6, "Masukkan nomor sertifikat.").max(40),
});

// --- helpers ----------------------------------------------------------------

/** Flatten a ZodError into `{ field: message }` for form display. */
export function fieldErrors(error: z.ZodError): Record<string, string> {
  const result: Record<string, string> = {};
  for (const issue of error.issues) {
    const key = issue.path.join(".") || "_form";
    if (!result[key]) result[key] = issue.message;
  }
  return result;
}

/** Convert FormData into a plain object, dropping empty strings. */
export function formDataToObject(formData: FormData): Record<string, unknown> {
  const result: Record<string, unknown> = {};
  for (const [key, value] of formData.entries()) {
    if (value instanceof File) continue;
    if (key.endsWith("[]")) {
      const arrayKey = key.slice(0, -2);
      const existing = result[arrayKey];
      const list = Array.isArray(existing) ? existing : [];
      list.push(value);
      result[arrayKey] = list;
    } else {
      result[key] = value;
    }
  }
  return result;
}
