import "server-only";
import { prisma } from "@/lib/db";
import type {
  AssignmentType,
  CodingLanguage,
  CourseLevel,
  PublishStatus,
  Role,
  SubmissionStatus,
} from "@prisma/client";

/**
 * Assignment, submission and grading reads.
 *
 * Visibility:
 *   • STUDENT — published assignments in courses they are enrolled in (or
 *               whose class they belong to), plus their own submission.
 *   • TEACHER — assignments in courses they own or classes they teach.
 *   • ADMIN   — everything.
 */

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

/** Prisma fragment: assignments the actor may read. */
function assignmentAccessFilter(scope: GradingScope) {
  if (scope.role === "ADMIN") return {};
  if (scope.role === "TEACHER") {
    return {
      course: {
        OR: [{ teacherId: scope.userId }, { classroom: { teacherId: scope.userId } }],
      },
    };
  }
  return {
    status: "PUBLISHED" as const,
    course: {
      OR: [
        { enrollments: { some: { studentId: scope.userId } } },
        { classroom: { enrollments: { some: { studentId: scope.userId, status: "ACTIVE" as const } } } },
      ],
    },
  };
}

export interface AssignmentListItem {
  id: string;
  title: string;
  type: AssignmentType;
  status: PublishStatus;
  maxScore: number;
  weight: number;
  dueAt: Date | null;
  allowLate: boolean;
  courseId: string;
  courseTitle: string;
  courseCoverColor: string;
  /** Staff only. */
  submissionCount: number;
  gradedCount: number;
  studentCount: number;
  /** Student only. */
  ownStatus: SubmissionStatus | null;
  ownScore: number | null;
  ownIsLate: boolean;
}

export interface AssignmentFilters {
  courseId?: string;
  type?: AssignmentType;
  status?: PublishStatus;
  search?: string;
  /** Student view: `todo` = not submitted, `done` = submitted/graded. */
  view?: "all" | "todo" | "done";
}

export async function listAssignments(
  scope: GradingScope,
  filters: AssignmentFilters = {}
): Promise<AssignmentListItem[]> {
  const assignments = await prisma.assignment.findMany({
    where: {
      AND: [
        assignmentAccessFilter(scope),
        filters.courseId ? { courseId: filters.courseId } : {},
        filters.type ? { type: filters.type } : {},
        filters.status && scope.role !== "STUDENT" ? { status: filters.status } : {},
        filters.search ? { title: { contains: filters.search, mode: "insensitive" as const } } : {},
      ],
    },
    orderBy: [{ dueAt: "asc" }, { createdAt: "desc" }],
    select: {
      id: true,
      title: true,
      type: true,
      status: true,
      maxScore: true,
      weight: true,
      dueAt: true,
      allowLate: true,
      courseId: true,
      course: {
        select: {
          title: true,
          coverColor: true,
          _count: { select: { enrollments: true } },
        },
      },
      _count: { select: { submissions: true } },
      submissions: {
        where: { studentId: scope.userId },
        select: { status: true, score: true, isLate: true },
        take: 1,
      },
    },
  });

  // Grading progress needs a second pass: count graded rows per assignment.
  const gradedCounts = await prisma.submission.groupBy({
    by: ["assignmentId"],
    where: {
      assignmentId: { in: assignments.map((assignment) => assignment.id) },
      status: { in: ["GRADED", "RETURNED"] },
    },
    _count: { _all: true },
  });
  const gradedByAssignment = new Map(
    gradedCounts.map((row) => [row.assignmentId, row._count._all])
  );

  const rows = assignments.map((assignment) => {
    const own = assignment.submissions[0];
    return {
      id: assignment.id,
      title: assignment.title,
      type: assignment.type,
      status: assignment.status,
      maxScore: assignment.maxScore,
      weight: assignment.weight,
      dueAt: assignment.dueAt,
      allowLate: assignment.allowLate,
      courseId: assignment.courseId,
      courseTitle: assignment.course.title,
      courseCoverColor: assignment.course.coverColor,
      submissionCount: assignment._count.submissions,
      gradedCount: gradedByAssignment.get(assignment.id) ?? 0,
      studentCount: assignment.course._count.enrollments,
      ownStatus: own?.status ?? null,
      ownScore: own?.score ?? null,
      ownIsLate: own?.isLate ?? false,
    };
  });

  if (scope.role !== "STUDENT" || !filters.view || filters.view === "all") return rows;

  return rows.filter((row) => {
    const submitted = row.ownStatus !== null && row.ownStatus !== "DRAFT";
    return filters.view === "todo" ? !submitted : submitted;
  });
}

export interface AssignmentDetail {
  id: string;
  title: string;
  description: string;
  instructions: string | null;
  type: AssignmentType;
  status: PublishStatus;
  maxScore: number;
  weight: number;
  dueAt: Date | null;
  allowLate: boolean;
  attachmentUrl: string | null;
  createdAt: Date;
  createdBy: { id: string; fullName: string };
  course: { id: string; title: string; coverColor: string };
  lesson: { id: string; title: string } | null;
  /**
   * Present only on a QUIZ assignment that has been authored. Drives the
   * student's route into the quiz runner instead of the file-upload form.
   */
  quiz: { id: string; questionCount: number } | null;
  canManage: boolean;
  stats: { submissionCount: number; gradedCount: number; studentCount: number; averageScore: number | null };
}

export async function getAssignment(
  scope: GradingScope,
  assignmentId: string
): Promise<AssignmentDetail | null> {
  const assignment = await prisma.assignment.findFirst({
    where: { AND: [{ id: assignmentId }, assignmentAccessFilter(scope)] },
    select: {
      id: true,
      title: true,
      description: true,
      instructions: true,
      type: true,
      status: true,
      maxScore: true,
      weight: true,
      dueAt: true,
      allowLate: true,
      attachmentUrl: true,
      createdAt: true,
      createdById: true,
      createdBy: { select: { id: true, fullName: true } },
      course: {
        select: {
          id: true,
          title: true,
          coverColor: true,
          teacherId: true,
          classroom: { select: { teacherId: true } },
          _count: { select: { enrollments: true } },
        },
      },
      lesson: { select: { id: true, title: true } },
      quiz: { select: { id: true, _count: { select: { questions: true } } } },
      _count: { select: { submissions: true } },
    },
  });

  if (!assignment) return null;

  const ownerIds = [
    assignment.course.teacherId,
    assignment.course.classroom?.teacherId,
  ].filter(Boolean) as string[];
  const canManage =
    scope.role === "ADMIN" ||
    (scope.role === "TEACHER" && ownerIds.includes(scope.userId));

  const [gradedCount, scoreAgg] = await Promise.all([
    prisma.submission.count({
      where: { assignmentId, status: { in: ["GRADED", "RETURNED"] } },
    }),
    prisma.submission.aggregate({
      where: { assignmentId, score: { not: null } },
      _avg: { score: true },
    }),
  ]);

  return {
    id: assignment.id,
    title: assignment.title,
    description: assignment.description,
    instructions: assignment.instructions,
    type: assignment.type,
    status: assignment.status,
    maxScore: assignment.maxScore,
    weight: assignment.weight,
    dueAt: assignment.dueAt,
    allowLate: assignment.allowLate,
    attachmentUrl: assignment.attachmentUrl,
    createdAt: assignment.createdAt,
    createdBy: assignment.createdBy,
    course: {
      id: assignment.course.id,
      title: assignment.course.title,
      coverColor: assignment.course.coverColor,
    },
    lesson: assignment.lesson,
    quiz: assignment.quiz
      ? { id: assignment.quiz.id, questionCount: assignment.quiz._count.questions }
      : null,
    canManage,
    stats: {
      submissionCount: assignment._count.submissions,
      gradedCount,
      studentCount: assignment.course._count.enrollments,
      averageScore: scoreAgg._avg.score === null ? null : Math.round(scoreAgg._avg.score * 10) / 10,
    },
  };
}

export interface SubmissionRow {
  id: string;
  studentId: string;
  studentName: string;
  studentUsername: string;
  avatarUrl: string | null;
  gradeLevel: string | null;
  status: SubmissionStatus;
  isLate: boolean;
  submittedAt: Date | null;
  score: number | null;
  feedback: string | null;
  hasFile: boolean;
  fileName: string | null;
  gradedAt: Date | null;
}

/** Every submission for an assignment, annotated with the student. */
export async function listSubmissions(assignmentId: string): Promise<SubmissionRow[]> {
  const submissions = await prisma.submission.findMany({
    where: { assignmentId },
    orderBy: [{ submittedAt: "asc" }],
    select: {
      id: true,
      studentId: true,
      status: true,
      isLate: true,
      submittedAt: true,
      score: true,
      feedback: true,
      fileUrl: true,
      fileName: true,
      gradedAt: true,
      student: {
        select: { fullName: true, username: true, avatarUrl: true, gradeLevel: true },
      },
    },
  });

  return submissions.map((submission) => ({
    id: submission.id,
    studentId: submission.studentId,
    studentName: submission.student.fullName,
    studentUsername: submission.student.username,
    avatarUrl: submission.student.avatarUrl,
    gradeLevel: submission.student.gradeLevel,
    status: submission.status,
    isLate: submission.isLate,
    submittedAt: submission.submittedAt,
    score: submission.score,
    feedback: submission.feedback,
    hasFile: Boolean(submission.fileUrl),
    fileName: submission.fileName,
    gradedAt: submission.gradedAt,
  }));
}

export interface MySubmission {
  id: string;
  content: string | null;
  fileUrl: string | null;
  fileName: string | null;
  fileSize: number | null;
  status: SubmissionStatus;
  isLate: boolean;
  submittedAt: Date | null;
  score: number | null;
  feedback: string | null;
  gradedAt: Date | null;
  gradedBy: string | null;
  comments: { id: string; body: string; authorName: string; createdAt: Date }[];
}

/** The signed-in student's own submission for an assignment, if any. */
export async function getMySubmission(
  assignmentId: string,
  studentId: string
): Promise<MySubmission | null> {
  const submission = await prisma.submission.findUnique({
    where: { assignmentId_studentId: { assignmentId, studentId } },
    select: {
      id: true,
      content: true,
      fileUrl: true,
      fileName: true,
      fileSize: true,
      status: true,
      isLate: true,
      submittedAt: true,
      score: true,
      feedback: true,
      gradedAt: true,
      gradedBy: { select: { fullName: true } },
      comments: {
        orderBy: { createdAt: "asc" },
        select: {
          id: true,
          body: true,
          createdAt: true,
          author: { select: { fullName: true } },
        },
      },
    },
  });

  if (!submission) return null;

  return {
    id: submission.id,
    content: submission.content,
    fileUrl: submission.fileUrl,
    fileName: submission.fileName,
    fileSize: submission.fileSize,
    status: submission.status,
    isLate: submission.isLate,
    submittedAt: submission.submittedAt,
    score: submission.score,
    feedback: submission.feedback,
    gradedAt: submission.gradedAt,
    gradedBy: submission.gradedBy?.fullName ?? null,
    comments: submission.comments.map((comment) => ({
      id: comment.id,
      body: comment.body,
      authorName: comment.author.fullName,
      createdAt: comment.createdAt,
    })),
  };
}

export interface GradingQueueItem {
  id: string;
  studentName: string;
  studentUsername: string;
  avatarUrl: string | null;
  assignmentId: string;
  assignmentTitle: string;
  /**
   * Drives where the queue's action button leads. A quiz cannot be graded
   * from the generic form, so its button opens the marked paper instead.
   */
  assignmentType: AssignmentType;
  courseTitle: string;
  maxScore: number;
  isLate: boolean;
  submittedAt: Date | null;
  status: SubmissionStatus;
}

/** Submissions awaiting a grade, across every course the actor manages. */
export async function listGradingQueue(
  scope: GradingScope,
  options: { courseId?: string; onlyUngraded?: boolean } = {}
): Promise<GradingQueueItem[]> {
  const submissions = await prisma.submission.findMany({
    where: {
      status: options.onlyUngraded === false ? { in: ["SUBMITTED", "LATE", "GRADED", "RETURNED"] } : { in: ["SUBMITTED", "LATE"] },
      assignment: {
        AND: [
          assignmentAccessFilter(scope),
          options.courseId ? { courseId: options.courseId } : {},
        ],
      },
    },
    orderBy: [{ submittedAt: "asc" }],
    select: {
      id: true,
      status: true,
      isLate: true,
      submittedAt: true,
      student: { select: { fullName: true, username: true, avatarUrl: true } },
      assignment: {
        select: { id: true, title: true, type: true, maxScore: true, course: { select: { title: true } } },
      },
    },
  });

  return submissions.map((submission) => ({
    id: submission.id,
    studentName: submission.student.fullName,
    studentUsername: submission.student.username,
    avatarUrl: submission.student.avatarUrl,
    assignmentId: submission.assignment.id,
    assignmentTitle: submission.assignment.title,
    assignmentType: submission.assignment.type,
    courseTitle: submission.assignment.course.title,
    maxScore: submission.assignment.maxScore,
    isLate: submission.isLate,
    submittedAt: submission.submittedAt,
    status: submission.status,
  }));
}

export interface SubmissionForGrading {
  id: string;
  content: string | null;
  fileUrl: string | null;
  fileName: string | null;
  fileSize: number | null;
  status: SubmissionStatus;
  isLate: boolean;
  submittedAt: Date | null;
  score: number | null;
  feedback: string | null;
  student: { id: string; fullName: string; username: string; avatarUrl: string | null };
  assignment: {
    id: string;
    title: string;
    type: AssignmentType;
    maxScore: number;
    dueAt: Date | null;
    courseTitle: string;
    courseId: string;
  };
  previousSubmissions: { id: string; score: number | null; submittedAt: Date | null; assignmentTitle: string }[];
}

/** One submission with everything a grader needs on a single screen. */
export async function getSubmissionForGrading(
  scope: GradingScope,
  submissionId: string
): Promise<SubmissionForGrading | null> {
  const submission = await prisma.submission.findFirst({
    where: { AND: [{ id: submissionId }, { assignment: assignmentAccessFilter(scope) }] },
    select: {
      id: true,
      content: true,
      fileUrl: true,
      fileName: true,
      fileSize: true,
      status: true,
      isLate: true,
      submittedAt: true,
      score: true,
      feedback: true,
      studentId: true,
      student: {
        select: { id: true, fullName: true, username: true, avatarUrl: true },
      },
      assignment: {
        select: {
          id: true,
          title: true,
          type: true,
          maxScore: true,
          dueAt: true,
          course: { select: { id: true, title: true } },
        },
      },
    },
  });

  if (!submission) return null;

  // Context: how this student has done on the course's other assignments.
  const previous = await prisma.submission.findMany({
    where: {
      studentId: submission.studentId,
      assignment: { courseId: submission.assignment.course.id },
      id: { not: submission.id },
      status: { in: ["GRADED", "RETURNED"] },
    },
    orderBy: { gradedAt: "desc" },
    take: 5,
    select: {
      id: true,
      score: true,
      submittedAt: true,
      assignment: { select: { title: true } },
    },
  });

  return {
    id: submission.id,
    content: submission.content,
    fileUrl: submission.fileUrl,
    fileName: submission.fileName,
    fileSize: submission.fileSize,
    status: submission.status,
    isLate: submission.isLate,
    submittedAt: submission.submittedAt,
    score: submission.score,
    feedback: submission.feedback,
    student: submission.student,
    assignment: {
      id: submission.assignment.id,
      title: submission.assignment.title,
      type: submission.assignment.type,
      maxScore: submission.assignment.maxScore,
      dueAt: submission.assignment.dueAt,
      courseTitle: submission.assignment.course.title,
      courseId: submission.assignment.course.id,
    },
    previousSubmissions: previous.map((row) => ({
      id: row.id,
      score: row.score,
      submittedAt: row.submittedAt,
      assignmentTitle: row.assignment.title,
    })),
  };
}

export interface GradebookCourse {
  id: string;
  title: string;
  coverColor: string;
  classroomName: string | null;
}

export interface GradebookColumn {
  id: string;
  title: string;
  type: AssignmentType;
  maxScore: number;
  weight: number;
  dueAt: Date | null;
}

export interface GradebookRow {
  studentId: string;
  studentName: string;
  username: string;
  avatarUrl: string | null;
  gradeLevel: string | null;
  /** assignmentId → score (null when not graded / not submitted). */
  scores: Record<string, number | null>;
  /** assignmentId → submission status. */
  statuses: Record<string, SubmissionStatus | null>;
  totalScore: number;
  totalPossible: number;
  percent: number | null;
  gradedCount: number;
  submittedCount: number;
}

export interface Gradebook {
  course: GradebookCourse;
  columns: GradebookColumn[];
  rows: GradebookRow[];
  classAverage: number | null;
  submissionRate: number;
}

/** Full grade matrix for one course: students × published assignments. */
export async function getGradebook(courseId: string): Promise<Gradebook | null> {
  const course = await prisma.course.findUnique({
    where: { id: courseId },
    select: {
      id: true,
      title: true,
      coverColor: true,
      classroom: { select: { name: true } },
      assignments: {
        where: { status: "PUBLISHED" },
        orderBy: [{ dueAt: "asc" }, { createdAt: "asc" }],
        select: {
          id: true,
          title: true,
          type: true,
          maxScore: true,
          weight: true,
          dueAt: true,
        },
      },
      enrollments: {
        orderBy: { enrolledAt: "asc" },
        select: {
          studentId: true,
          student: {
            select: { id: true, fullName: true, username: true, avatarUrl: true, gradeLevel: true },
          },
        },
      },
    },
  });

  if (!course) return null;

  const submissions = await prisma.submission.findMany({
    where: { assignmentId: { in: course.assignments.map((assignment) => assignment.id) } },
    select: { assignmentId: true, studentId: true, score: true, status: true },
  });

  const byStudent = new Map<string, Map<string, { score: number | null; status: SubmissionStatus }>>();
  for (const submission of submissions) {
    const forStudent = byStudent.get(submission.studentId) ?? new Map();
    forStudent.set(submission.assignmentId, {
      score: submission.score,
      status: submission.status,
    });
    byStudent.set(submission.studentId, forStudent);
  }

  const columns: GradebookColumn[] = course.assignments.map((assignment) => ({
    id: assignment.id,
    title: assignment.title,
    type: assignment.type,
    maxScore: assignment.maxScore,
    weight: assignment.weight,
    dueAt: assignment.dueAt,
  }));

  const rows: GradebookRow[] = course.enrollments.map((enrollment) => {
    const forStudent = byStudent.get(enrollment.studentId) ?? new Map();
    const scores: Record<string, number | null> = {};
    const statuses: Record<string, SubmissionStatus | null> = {};

    let weightedEarned = 0;
    let weightedPossible = 0;
    let gradedCount = 0;
    let submittedCount = 0;

    for (const column of columns) {
      const entry = forStudent.get(column.id);
      scores[column.id] = entry?.score ?? null;
      statuses[column.id] = entry?.status ?? null;

      if (entry && entry.status !== "DRAFT") submittedCount += 1;
      if (entry?.score !== null && entry?.score !== undefined) {
        gradedCount += 1;
        weightedEarned += entry.score * column.weight;
        weightedPossible += column.maxScore * column.weight;
      }
    }

    const percent = weightedPossible === 0 ? null : Math.round((weightedEarned / weightedPossible) * 1000) / 10;

    return {
      studentId: enrollment.student.id,
      studentName: enrollment.student.fullName,
      username: enrollment.student.username,
      avatarUrl: enrollment.student.avatarUrl,
      gradeLevel: enrollment.student.gradeLevel,
      scores,
      statuses,
      totalScore: Math.round(weightedEarned * 10) / 10,
      totalPossible: weightedPossible,
      percent,
      gradedCount,
      submittedCount,
    };
  });

  const scored = rows.map((row) => row.percent).filter((value): value is number => value !== null);
  const classAverage =
    scored.length === 0 ? null : Math.round((scored.reduce((a, b) => a + b, 0) / scored.length) * 10) / 10;

  const possibleSubmissions = rows.length * columns.length;
  const actualSubmissions = rows.reduce((sum, row) => sum + row.submittedCount, 0);

  return {
    course: {
      id: course.id,
      title: course.title,
      coverColor: course.coverColor,
      classroomName: course.classroom?.name ?? null,
    },
    columns,
    rows,
    classAverage,
    submissionRate:
      possibleSubmissions === 0 ? 0 : Math.round((actualSubmissions / possibleSubmissions) * 100),
  };
}

export interface StudentGradeRow {
  assignmentId: string;
  title: string;
  courseTitle: string;
  type: AssignmentType;
  maxScore: number;
  weight: number;
  dueAt: Date | null;
  status: SubmissionStatus | null;
  score: number | null;
  percent: number | null;
  feedback: string | null;
}

/** A single student's own grade list, across every course. */
export async function listMyGrades(studentId: string): Promise<StudentGradeRow[]> {
  const submissions = await prisma.submission.findMany({
    where: { studentId },
    orderBy: [{ submittedAt: "desc" }],
    select: {
      status: true,
      score: true,
      feedback: true,
      assignment: {
        select: {
          id: true,
          title: true,
          type: true,
          maxScore: true,
          weight: true,
          dueAt: true,
          course: { select: { title: true } },
        },
      },
    },
  });

  return submissions.map((submission) => {
    const { assignment } = submission;
    return {
      assignmentId: assignment.id,
      title: assignment.title,
      courseTitle: assignment.course.title,
      type: assignment.type,
      maxScore: assignment.maxScore,
      weight: assignment.weight,
      dueAt: assignment.dueAt,
      status: submission.status,
      score: submission.score,
      percent:
        submission.score === null
          ? null
          : Math.round((submission.score / assignment.maxScore) * 1000) / 10,
      feedback: submission.feedback,
    };
  });
}

export interface GradebookCourseOption {
  id: string;
  title: string;
}

/** Courses the actor can open a gradebook for. */
export async function listGradebookCourses(scope: GradingScope): Promise<GradebookCourseOption[]> {
  const courses = await prisma.course.findMany({
    where:
      scope.role === "ADMIN"
        ? {}
        : {
            OR: [
              { teacherId: scope.userId },
              { classroom: { teacherId: scope.userId } },
            ],
          },
    orderBy: { title: "asc" },
    select: { id: true, title: true },
  });
  return courses;
}

export interface AssignmentCourseOption {
  id: string;
  title: string;
  coverColor: string;
}

/** Courses the actor may attach an assignment to. */
export async function listAssignableCourses(
  scope: GradingScope
): Promise<AssignmentCourseOption[]> {
  const courses = await prisma.course.findMany({
    where:
      scope.role === "ADMIN"
        ? {}
        : {
            OR: [
              { teacherId: scope.userId },
              { classroom: { teacherId: scope.userId } },
            ],
          },
    orderBy: { title: "asc" },
    select: { id: true, title: true, coverColor: true },
  });
  return courses;
}

/** Lessons within a course, for the optional assignment↔lesson link. */
export async function listCourseLessonOptions(courseId: string) {
  return prisma.lesson.findMany({
    where: { courseId },
    orderBy: [{ orderIndex: "asc" }],
    select: { id: true, title: true },
  });
}

/** Coding projects that could satisfy a CODING-type assignment. */
export interface CodingProjectOption {
  id: string;
  title: string;
  language: CodingLanguage;
  difficulty: CourseLevel;
}

export async function listCodingProjectOptions(courseId?: string): Promise<CodingProjectOption[]> {
  return prisma.codingProject.findMany({
    where: courseId ? { courseId } : {},
    orderBy: [{ orderIndex: "asc" }],
    select: { id: true, title: true, language: true, difficulty: true },
  });
}
