import { randomBytes } from "node:crypto";
import { prisma } from "@/lib/db";

/**
 * Certificate issuing.
 *
 * Deliberately free of `server-only` and `next/headers` so the seed script can
 * call it too — the rules for "when is a certificate earned" must live in one
 * place, whether the trigger is a student finishing a lesson or a re-seed.
 */

/**
 * Alphabet for the public serial.
 *
 * Excludes 0/O/1/I/L because a verification code gets read off a printed sheet
 * and typed back in by hand; ambiguous glyphs turn into support requests.
 */
const SERIAL_ALPHABET = "23456789ABCDEFGHJKMNPQRSTVWXYZ";
const SERIAL_LENGTH = 6;

/**
 * Build a serial like `TC-CERT-2026-K7M2Q9`.
 *
 * The random suffix matters: the public verification page is unauthenticated,
 * so a sequential number would let anyone walk the whole roll and read every
 * student's name. Six characters of this alphabet is ~1e9 combinations.
 */
export function generateCertificateSerial(year = new Date().getFullYear()): string {
  const bytes = randomBytes(SERIAL_LENGTH);
  let suffix = "";
  for (let index = 0; index < SERIAL_LENGTH; index += 1) {
    suffix += SERIAL_ALPHABET[bytes[index] % SERIAL_ALPHABET.length];
  }
  return `TC-CERT-${year}-${suffix}`;
}

/** Normalise a serial typed by a human: trim, uppercase, collapse spacing. */
export function normaliseSerial(raw: string): string {
  return raw.trim().toUpperCase().replace(/\s+/g, "");
}

export interface EnsureCertificateResult {
  certificateId: string;
  serial: string;
  created: boolean;
}

/**
 * Issue a certificate for a completed course enrolment, or return the existing
 * one. Idempotent: the `(studentId, courseId)` unique key means calling this on
 * every lesson completion cannot mint duplicates.
 *
 * Returns `null` when the student has not actually finished the course — the
 * caller is expected to treat that as "nothing to do", not as an error.
 */
export async function ensureCertificateForCourse(
  studentId: string,
  courseId: string,
  issuedById?: string | null
): Promise<EnsureCertificateResult | null> {
  const enrollment = await prisma.courseEnrollment.findUnique({
    where: { courseId_studentId: { courseId, studentId } },
    select: {
      id: true,
      progress: true,
      status: true,
      completedAt: true,
      student: { select: { fullName: true } },
      course: {
        select: {
          title: true,
          level: true,
          teacher: { select: { fullName: true } },
        },
      },
    },
  });

  if (!enrollment) return null;

  // Completion is the gate. `status` alone is not enough: an enrolment can be
  // COMPLETED with a stale `progress` if the course gained lessons afterwards,
  // and we only ever want to certify a genuine finish.
  const isComplete = enrollment.status === "COMPLETED" && enrollment.progress >= 100;
  if (!isComplete) return null;

  const existing = await prisma.certificate.findUnique({
    where: { studentId_courseId: { studentId, courseId } },
    select: { id: true, serial: true },
  });

  if (existing) {
    return { certificateId: existing.id, serial: existing.serial, created: false };
  }

  const [lessonCount, gradedAverage, xpAggregate] = await Promise.all([
    prisma.lesson.count({ where: { courseId, status: "PUBLISHED" } }),
    prisma.submission.aggregate({
      where: {
        studentId,
        score: { not: null },
        assignment: { courseId },
      },
      _avg: { score: true },
      _count: { _all: true },
    }),
    // XP is recorded per lesson, so sum the ledger for this course's lessons.
    prisma.xpEvent.aggregate({
      where: {
        userId: studentId,
        OR: [
          { refType: "lesson", refId: { in: await lessonIdsOf(courseId) } },
          { refId: courseId },
        ],
      },
      _sum: { amount: true },
    }),
  ]);

  // Average across graded work, expressed as a percentage of full marks so a
  // course with 100-point assignments and one with 10-point ones compare.
  const maxScore = await prisma.assignment.aggregate({
    where: { courseId, submissions: { some: { studentId, score: { not: null } } } },
    _avg: { maxScore: true },
  });

  const averageMax = maxScore._avg.maxScore ?? 0;
  const finalScore =
    gradedAverage._avg.score === null || averageMax <= 0
      ? null
      : Math.round((gradedAverage._avg.score / averageMax) * 100);

  // Retry on the (vanishingly unlikely) serial collision rather than failing
  // the student's action.
  for (let attempt = 0; attempt < 5; attempt += 1) {
    try {
      const certificate = await prisma.certificate.create({
        data: {
          serial: generateCertificateSerial(),
          studentId,
          courseId,
          issuedById: issuedById ?? null,
          studentName: enrollment.student.fullName,
          courseTitle: enrollment.course.title,
          courseLevel: enrollment.course.level,
          teacherName: enrollment.course.teacher.fullName,
          finalScore,
          lessonCount,
          xpEarned: xpAggregate._sum.amount ?? 0,
        },
        select: { id: true, serial: true },
      });
      return { certificateId: certificate.id, serial: certificate.serial, created: true };
    } catch (error) {
      const message = error instanceof Error ? error.message : "";
      // P2002 = unique violation. Only the serial is worth retrying; a clash on
      // (studentId, courseId) means a concurrent call already issued it.
      if (!message.includes("P2002")) throw error;
      const raced = await prisma.certificate.findUnique({
        where: { studentId_courseId: { studentId, courseId } },
        select: { id: true, serial: true },
      });
      if (raced) {
        return { certificateId: raced.id, serial: raced.serial, created: false };
      }
    }
  }

  return null;
}

/** Lesson ids for a course — used to attribute XP to the right certificate. */
async function lessonIdsOf(courseId: string): Promise<string[]> {
  const lessons = await prisma.lesson.findMany({
    where: { courseId },
    select: { id: true },
  });
  return lessons.map((lesson) => lesson.id);
}

/** Revoke a certificate. Kept here so the reason is always recorded. */
export async function revokeCertificate(
  certificateId: string,
  note: string | null
): Promise<void> {
  await prisma.certificate.update({
    where: { id: certificateId },
    data: { status: "REVOKED", revokedAt: new Date(), revokeNote: note },
  });
}

/** Restore a revoked certificate. */
export async function reinstateCertificate(certificateId: string): Promise<void> {
  await prisma.certificate.update({
    where: { id: certificateId },
    data: { status: "ISSUED", revokedAt: null, revokeNote: null },
  });
}
