import "server-only";
import { prisma } from "@/lib/db";
import type { CertificateStatus, CourseLevel, Role } from "@prisma/client";
import { normaliseSerial } from "@/lib/certificates";

/**
 * Certificate reads.
 *
 * Two audiences with different rules:
 *  - the holder sees their own certificates;
 *  - staff see the whole register and may revoke.
 * The public verification lookup is separate and deliberately returns less.
 */

export interface CertificateScope {
  userId: string;
  role: Role;
}

// ---------------------------------------------------------------------------
// Student view
// ---------------------------------------------------------------------------

export interface MyCertificateItem {
  id: string;
  serial: string;
  courseId: string;
  courseTitle: string;
  courseLevel: CourseLevel;
  teacherName: string;
  status: CertificateStatus;
  finalScore: number | null;
  issuedAt: Date;
  revokedAt: Date | null;
}

export async function listMyCertificates(userId: string): Promise<MyCertificateItem[]> {
  const rows = await prisma.certificate.findMany({
    where: { studentId: userId },
    orderBy: { issuedAt: "desc" },
    select: {
      id: true,
      serial: true,
      courseId: true,
      courseTitle: true,
      courseLevel: true,
      teacherName: true,
      status: true,
      finalScore: true,
      issuedAt: true,
      revokedAt: true,
    },
  });
  return rows;
}

/**
 * Courses the student has finished but that have no certificate yet.
 *
 * Without this the student would see nothing and assume the feature is broken;
 * the page offers a "terbitkan" button instead. Normally unreachable because
 * issuing is automatic, but it covers enrolments completed before this feature
 * existed, and any issue that failed mid-flight.
 */
export interface PendingCertificateItem {
  courseId: string;
  courseTitle: string;
  courseLevel: CourseLevel;
  completedAt: Date;
}

export async function listPendingCertificates(
  userId: string
): Promise<PendingCertificateItem[]> {
  const rows = await prisma.courseEnrollment.findMany({
    where: {
      studentId: userId,
      status: "COMPLETED",
      progress: { gte: 100 },
      course: { certificates: { none: { studentId: userId } } },
    },
    orderBy: { completedAt: "desc" },
    select: {
      completedAt: true,
      course: { select: { id: true, title: true, level: true } },
    },
  });

  return rows.map((row) => ({
    courseId: row.course.id,
    courseTitle: row.course.title,
    courseLevel: row.course.level,
    completedAt: row.completedAt ?? new Date(),
  }));
}

// ---------------------------------------------------------------------------
// Certificate detail
// ---------------------------------------------------------------------------

export interface CertificateDetail {
  id: string;
  serial: string;
  status: CertificateStatus;
  studentId: string;
  studentName: string;
  courseId: string;
  courseTitle: string;
  courseLevel: CourseLevel;
  teacherName: string;
  finalScore: number | null;
  lessonCount: number;
  xpEarned: number;
  issuedAt: Date;
  revokedAt: Date | null;
  revokeNote: string | null;
  issuedByName: string | null;
  /** Course completion date, for the "menyelesaikan pada" line. */
  completedAt: Date | null;
}

/**
 * Read one certificate.
 *
 * `scope` decides visibility, and it must match the register exactly:
 *  - the holder sees their own;
 *  - a teacher sees only certificates for courses they teach;
 *  - an administrator sees everything.
 *
 * A caller who may not read it gets `null`, which the page turns into
 * `notFound()` — so the existence of the record is never disclosed.
 */
export async function getCertificate(
  scope: CertificateScope,
  certificateId: string
): Promise<CertificateDetail | null> {
  const certificate = await prisma.certificate.findUnique({
    where: { id: certificateId },
    select: {
      id: true,
      serial: true,
      status: true,
      studentId: true,
      studentName: true,
      courseId: true,
      courseTitle: true,
      courseLevel: true,
      teacherName: true,
      finalScore: true,
      lessonCount: true,
      xpEarned: true,
      issuedAt: true,
      revokedAt: true,
      revokeNote: true,
      issuedBy: { select: { fullName: true } },
      course: { select: { teacherId: true } },
    },
  });

  if (!certificate) return null;

  const isHolder = certificate.studentId === scope.userId;
  const isAdmin = scope.role === "ADMIN";
  // A teacher's reach stops at the courses they teach. Without this the
  // register would hide other teachers' classes while a direct URL still
  // exposed them — a certificate carries a student's name and score.
  const isCourseTeacher =
    scope.role === "TEACHER" && certificate.course.teacherId === scope.userId;

  if (!isHolder && !isAdmin && !isCourseTeacher) return null;

  // Completion date lives on the enrolment, which the relation above cannot
  // reach directly (it is keyed by the student too), so it is fetched here.
  const enrollment = await prisma.courseEnrollment.findUnique({
    where: { courseId_studentId: { courseId: certificate.courseId, studentId: certificate.studentId } },
    select: { completedAt: true },
  });

  return {
    id: certificate.id,
    serial: certificate.serial,
    status: certificate.status,
    studentId: certificate.studentId,
    studentName: certificate.studentName,
    courseId: certificate.courseId,
    courseTitle: certificate.courseTitle,
    courseLevel: certificate.courseLevel,
    teacherName: certificate.teacherName,
    finalScore: certificate.finalScore,
    lessonCount: certificate.lessonCount,
    xpEarned: certificate.xpEarned,
    issuedAt: certificate.issuedAt,
    revokedAt: certificate.revokedAt,
    revokeNote: certificate.revokeNote,
    issuedByName: certificate.issuedBy?.fullName ?? null,
    completedAt: enrollment?.completedAt ?? null,
  };
}

// ---------------------------------------------------------------------------
// Staff register
// ---------------------------------------------------------------------------

export interface CertificateRegisterRow {
  id: string;
  serial: string;
  studentName: string;
  studentUsername: string;
  courseTitle: string;
  courseLevel: CourseLevel;
  status: CertificateStatus;
  finalScore: number | null;
  issuedAt: Date;
}

export interface CertificateRegisterFilters {
  status?: CertificateStatus;
  courseId?: string;
  /** Free-text match on student name, username, or serial. */
  search?: string;
}

/**
 * The register, scoped by role.
 *
 * An administrator sees every certificate ever issued. A teacher sees only the
 * ones for courses they teach — a certificate names the student and their
 * score, so an unscoped register would leak other teachers' classes.
 */
export async function listCertificateRegister(
  scope: CertificateScope,
  filters: CertificateRegisterFilters = {}
): Promise<CertificateRegisterRow[]> {
  const search = filters.search?.trim();
  const courseScope = scope.role === "TEACHER" ? { course: { teacherId: scope.userId } } : {};

  const rows = await prisma.certificate.findMany({
    where: {
      ...courseScope,
      status: filters.status,
      courseId: filters.courseId,
      ...(search
        ? {
            OR: [
              { studentName: { contains: search, mode: "insensitive" as const } },
              { courseTitle: { contains: search, mode: "insensitive" as const } },
              { serial: { contains: normaliseSerial(search), mode: "insensitive" as const } },
              { student: { username: { contains: search, mode: "insensitive" as const } } },
            ],
          }
        : {}),
    },
    orderBy: { issuedAt: "desc" },
    select: {
      id: true,
      serial: true,
      studentName: true,
      courseTitle: true,
      courseLevel: true,
      status: true,
      finalScore: true,
      issuedAt: true,
      student: { select: { username: true } },
    },
  });

  return rows.map((row) => ({
    id: row.id,
    serial: row.serial,
    studentName: row.studentName,
    studentUsername: row.student.username,
    courseTitle: row.courseTitle,
    courseLevel: row.courseLevel,
    status: row.status,
    finalScore: row.finalScore,
    issuedAt: row.issuedAt,
  }));
}

export interface CertificateStats {
  issued: number;
  revoked: number;
  thisMonth: number;
  courseCount: number;
}

export async function getCertificateStats(
  scope: CertificateScope
): Promise<CertificateStats> {
  const startOfMonth = new Date();
  startOfMonth.setDate(1);
  startOfMonth.setHours(0, 0, 0, 0);

  const courseScope = scope.role === "TEACHER" ? { course: { teacherId: scope.userId } } : {};

  const [issued, revoked, thisMonth, courseGroups] = await Promise.all([
    prisma.certificate.count({ where: { ...courseScope, status: "ISSUED" } }),
    prisma.certificate.count({ where: { ...courseScope, status: "REVOKED" } }),
    prisma.certificate.count({ where: { ...courseScope, issuedAt: { gte: startOfMonth } } }),
    prisma.certificate.groupBy({ by: ["courseId"], where: courseScope }),
  ]);

  return { issued, revoked, thisMonth, courseCount: courseGroups.length };
}

/** Courses that already have at least one certificate — for the filter menu. */
export interface CertificateCourseOption {
  id: string;
  title: string;
  count: number;
}

export async function listCertificateCourses(
  scope: CertificateScope
): Promise<CertificateCourseOption[]> {
  const courseScope = scope.role === "TEACHER" ? { course: { teacherId: scope.userId } } : {};

  const groups = await prisma.certificate.groupBy({
    by: ["courseId"],
    where: courseScope,
    _count: { _all: true },
  });

  if (groups.length === 0) return [];

  const courses = await prisma.course.findMany({
    where: { id: { in: groups.map((group) => group.courseId) } },
    select: { id: true, title: true },
  });
  const titleById = new Map(courses.map((course) => [course.id, course.title]));

  return groups
    .map((group) => ({
      id: group.courseId,
      title: titleById.get(group.courseId) ?? "Kursus",
      count: group._count._all,
    }))
    .sort((a, b) => b.count - a.count);
}

// ---------------------------------------------------------------------------
// Public verification
// ---------------------------------------------------------------------------

export interface VerifiedCertificate {
  serial: string;
  studentName: string;
  courseTitle: string;
  courseLevel: CourseLevel;
  teacherName: string;
  finalScore: number | null;
  issuedAt: Date;
  status: CertificateStatus;
}

/**
 * Look up a certificate by its printed serial, for the public page.
 *
 * Returns revoked certificates too, with their status, so a verifier holding
 * paper that was later withdrawn learns that — silently reporting "not found"
 * would suggest the document was forged.
 */
export async function verifyCertificateBySerial(
  rawSerial: string
): Promise<VerifiedCertificate | null> {
  const serial = normaliseSerial(rawSerial);
  if (serial.length < 6) return null;

  const certificate = await prisma.certificate.findUnique({
    where: { serial },
    select: {
      serial: true,
      studentName: true,
      courseTitle: true,
      courseLevel: true,
      teacherName: true,
      finalScore: true,
      issuedAt: true,
      status: true,
    },
  });

  return certificate;
}
