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

/**
 * Course reads.
 *
 * Access rules are applied in SQL rather than post-filtered in the page so an
 * unauthorised row can never be serialised into the RSC payload:
 *   • ADMIN   — every course.
 *   • TEACHER — courses they authored, plus courses in classes they teach.
 *   • STUDENT — courses they are enrolled in, plus courses attached to a class
 *               they belong to (class membership grants course access).
 */

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

/**
 * Canonical course ordering.
 *
 * Every list that shows courses uses this so the same course never appears in a
 * different position on different pages. Drafts sort after published courses,
 * then the curriculum's own `orderIndex`, with the title as a stable tiebreak.
 */
export const COURSE_ORDER = [
  { status: "asc" as const },
  { orderIndex: "asc" as const },
  { title: "asc" as const },
];

export interface CourseListItem {
  id: string;
  title: string;
  slug: string;
  summary: string | null;
  coverColor: string;
  level: CourseLevel;
  language: CodingLanguage;
  status: PublishStatus;
  estimatedHours: number;
  lessonCount: number;
  studentCount: number;
  teacherName: string;
  classroomName: string | null;
  /** Student's own completion, 0–100. Null for staff. */
  progress: number | null;
  /** True when the signed-in student is enrolled. */
  enrolled: boolean;
}

export interface CourseFilters {
  status?: PublishStatus;
  level?: CourseLevel;
  classroomId?: string;
  search?: string;
}

/** Prisma `where` fragment expressing which courses the actor may read. */
function courseAccessFilter(scope: CourseScope) {
  if (scope.role === "ADMIN") return {};
  if (scope.role === "TEACHER") {
    return {
      OR: [
        { teacherId: scope.userId },
        { classroom: { teacherId: scope.userId } },
      ],
    };
  }
  return {
    OR: [
      { enrollments: { some: { studentId: scope.userId } } },
      { classroom: { enrollments: { some: { studentId: scope.userId, status: "ACTIVE" as const } } } },
    ],
  };
}

export async function listCourses(
  scope: CourseScope,
  filters: CourseFilters = {}
): Promise<CourseListItem[]> {
  const access = courseAccessFilter(scope);

  const courses = await prisma.course.findMany({
    where: {
      AND: [
        access,
        filters.status ? { status: filters.status } : {},
        filters.level ? { level: filters.level } : {},
        filters.classroomId ? { classroomId: filters.classroomId } : {},
        filters.search
          ? {
              OR: [
                { title: { contains: filters.search, mode: "insensitive" as const } },
                { summary: { contains: filters.search, mode: "insensitive" as const } },
              ],
            }
          : {},
      ],
    },
    orderBy: COURSE_ORDER,
    select: {
      id: true,
      title: true,
      slug: true,
      summary: true,
      coverColor: true,
      level: true,
      language: true,
      status: true,
      estimatedHours: true,
      teacher: { select: { fullName: true } },
      classroom: { select: { name: true } },
      _count: { select: { lessons: true, enrollments: true } },
      // Always selected (with a self-filter) so the row type stays uniform
      // across roles; only students' values are actually read.
      enrollments: { where: { studentId: scope.userId }, select: { progress: true }, take: 1 },
    },
  });

  return courses.map((course) => {
    const own = course.enrollments[0];
    return {
      id: course.id,
      title: course.title,
      slug: course.slug,
      summary: course.summary,
      coverColor: course.coverColor,
      level: course.level,
      language: course.language,
      status: course.status,
      estimatedHours: course.estimatedHours,
      lessonCount: course._count.lessons,
      studentCount: course._count.enrollments,
      teacherName: course.teacher.fullName,
      classroomName: course.classroom?.name ?? null,
      progress: scope.role === "STUDENT" ? (own?.progress ?? 0) : null,
      enrolled: scope.role === "STUDENT" ? Boolean(own) : true,
    };
  });
}

export interface CourseDetail {
  id: string;
  title: string;
  slug: string;
  summary: string | null;
  description: string | null;
  coverColor: string;
  level: CourseLevel;
  language: CodingLanguage;
  status: PublishStatus;
  estimatedHours: number;
  tags: string[];
  publishedAt: Date | null;
  createdAt: Date;
  teacher: { id: string; fullName: string; username: string };
  classroom: { id: string; name: string; joinCode: string } | null;
  /** True when the actor may edit/delete this course. */
  canManage: boolean;
  /** Student's own enrolment, when present. */
  enrollment: { progress: number; status: string } | null;
  stats: {
    lessonCount: number;
    studentCount: number;
    assignmentCount: number;
    projectCount: number;
  };
}

export async function getCourse(
  scope: CourseScope,
  courseId: string
): Promise<CourseDetail | null> {
  const course = await prisma.course.findFirst({
    where: { AND: [{ id: courseId }, courseAccessFilter(scope)] },
    select: {
      id: true,
      title: true,
      slug: true,
      summary: true,
      description: true,
      coverColor: true,
      level: true,
      language: true,
      status: true,
      estimatedHours: true,
      tags: true,
      publishedAt: true,
      createdAt: true,
      teacherId: true,
      teacher: { select: { id: true, fullName: true, username: true } },
      classroom: { select: { id: true, name: true, joinCode: true, teacherId: true } },
      _count: {
        select: { lessons: true, enrollments: true, assignments: true, projects: true },
      },
      enrollments: {
        where: { studentId: scope.userId },
        select: { progress: true, status: true },
        take: 1,
      },
    },
  });

  if (!course) return null;

  const own = course.enrollments[0];
  const canManage =
    scope.role === "ADMIN" ||
    (scope.role === "TEACHER" &&
      (course.teacherId === scope.userId || course.classroom?.teacherId === scope.userId));

  return {
    id: course.id,
    title: course.title,
    slug: course.slug,
    summary: course.summary,
    description: course.description,
    coverColor: course.coverColor,
    level: course.level,
    language: course.language,
    status: course.status,
    estimatedHours: course.estimatedHours,
    tags: course.tags,
    publishedAt: course.publishedAt,
    createdAt: course.createdAt,
    teacher: course.teacher,
    classroom: course.classroom
      ? { id: course.classroom.id, name: course.classroom.name, joinCode: course.classroom.joinCode }
      : null,
    canManage,
    enrollment: own ? { progress: own.progress, status: own.status } : null,
    stats: {
      lessonCount: course._count.lessons,
      studentCount: course._count.enrollments,
      assignmentCount: course._count.assignments,
      projectCount: course._count.projects,
    },
  };
}

export interface CourseModule {
  id: string;
  title: string;
  description: string | null;
  orderIndex: number;
  lessons: CourseLesson[];
}

export interface CourseLesson {
  id: string;
  title: string;
  slug: string;
  summary: string | null;
  type: string;
  durationMinutes: number;
  orderIndex: number;
  isPreview: boolean;
  status: PublishStatus;
  /** Student-only: their progress on this lesson. */
  progressStatus: string | null;
  progressPercent: number;
}

export interface CourseOutline {
  modules: CourseModule[];
  /** Lessons not attached to any module. */
  looseLessons: CourseLesson[];
}

/** Full curriculum tree, with the student's own progress folded in. */
export async function getCourseOutline(
  scope: CourseScope,
  courseId: string
): Promise<CourseOutline> {
  // The signature promises scope enforcement, so apply it rather than relying
  // on the caller having pre-authorized via getCourse.
  const readable = await prisma.course.findFirst({
    where: { id: courseId, ...courseAccessFilter(scope) },
    select: { id: true },
  });
  if (!readable) return { modules: [], looseLessons: [] };

  const [modules, lessons] = await Promise.all([
    prisma.module.findMany({
      where: { courseId },
      orderBy: { orderIndex: "asc" },
      select: { id: true, title: true, description: true, orderIndex: true },
    }),
    prisma.lesson.findMany({
      where: {
        courseId,
        // Students never see drafts.
        ...(scope.role === "STUDENT" ? { status: "PUBLISHED" as const } : {}),
      },
      orderBy: [{ orderIndex: "asc" }, { createdAt: "asc" }],
      select: {
        id: true,
        moduleId: true,
        title: true,
        slug: true,
        summary: true,
        type: true,
        durationMinutes: true,
        orderIndex: true,
        isPreview: true,
        status: true,
        progress: {
          where: { studentId: scope.userId },
          select: { status: true, progressPercent: true },
          take: 1,
        },
      },
    }),
  ]);

  const toLesson = (lesson: (typeof lessons)[number]): CourseLesson => {
    const own = lesson.progress[0];
    return {
      id: lesson.id,
      title: lesson.title,
      slug: lesson.slug,
      summary: lesson.summary,
      type: lesson.type,
      durationMinutes: lesson.durationMinutes,
      orderIndex: lesson.orderIndex,
      isPreview: lesson.isPreview,
      status: lesson.status,
      progressStatus: own?.status ?? null,
      progressPercent: own?.progressPercent ?? 0,
    };
  };

  return {
    modules: modules.map((module) => ({
      id: module.id,
      title: module.title,
      description: module.description,
      orderIndex: module.orderIndex,
      lessons: lessons.filter((lesson) => lesson.moduleId === module.id).map(toLesson),
    })),
    looseLessons: lessons.filter((lesson) => lesson.moduleId === null).map(toLesson),
  };
}

export interface CourseClassroomOption {
  id: string;
  name: string;
}

/** Classrooms the actor may attach a course to. */
export async function listClassroomOptions(scope: CourseScope): Promise<CourseClassroomOption[]> {
  const classrooms = await prisma.classroom.findMany({
    where: {
      archivedAt: null,
      ...(scope.role === "ADMIN" ? {} : { teacherId: scope.userId }),
    },
    orderBy: { name: "asc" },
    select: { id: true, name: true },
  });
  return classrooms;
}

export interface CourseAssignmentRow {
  id: string;
  title: string;
  type: string;
  maxScore: number;
  dueAt: Date | null;
  status: PublishStatus;
  submissionCount: number;
  /** Student-only: their own submission state, when one exists. */
  ownStatus: string | null;
  ownScore: number | null;
}

/** Assignments belonging to a course, annotated for the current viewer. */
export async function listCourseAssignments(
  scope: CourseScope,
  courseId: string
): Promise<CourseAssignmentRow[]> {
  const assignments = await prisma.assignment.findMany({
    where: {
      courseId,
      // Apply the scope the signature promises; callers should not have to
      // pre-authorize for this to be safe.
      course: courseAccessFilter(scope),
      ...(scope.role === "STUDENT" ? { status: "PUBLISHED" as const } : {}),
    },
    orderBy: [{ dueAt: "asc" }, { createdAt: "desc" }],
    select: {
      id: true,
      title: true,
      type: true,
      maxScore: true,
      dueAt: true,
      status: true,
      _count: { select: { submissions: true } },
      submissions: {
        where: { studentId: scope.userId },
        select: { status: true, score: true },
        take: 1,
      },
    },
  });

  return assignments.map((assignment) => ({
    id: assignment.id,
    title: assignment.title,
    type: assignment.type,
    maxScore: assignment.maxScore,
    dueAt: assignment.dueAt,
    status: assignment.status,
    submissionCount: assignment._count.submissions,
    ownStatus: assignment.submissions[0]?.status ?? null,
    ownScore: assignment.submissions[0]?.score ?? null,
  }));
}

export interface CourseStudentRow {
  id: string;
  fullName: string;
  username: string;
  avatarUrl: string | null;
  gradeLevel: string | null;
  progress: number;
  status: string;
  enrolledAt: Date;
}

/** Enrolled students with their course progress. */
export async function listCourseStudents(courseId: string): Promise<CourseStudentRow[]> {
  const enrollments = await prisma.courseEnrollment.findMany({
    where: { courseId },
    orderBy: { enrolledAt: "asc" },
    select: {
      progress: true,
      status: true,
      enrolledAt: true,
      student: {
        select: { id: true, fullName: true, username: true, avatarUrl: true, gradeLevel: true },
      },
    },
  });

  return enrollments.map((enrollment) => ({
    id: enrollment.student.id,
    fullName: enrollment.student.fullName,
    username: enrollment.student.username,
    avatarUrl: enrollment.student.avatarUrl,
    gradeLevel: enrollment.student.gradeLevel,
    progress: enrollment.progress,
    status: enrollment.status,
    enrolledAt: enrollment.enrolledAt,
  }));
}

/** Every student in the system, for manual enrolment. */
export async function listEnrollableStudents(courseId: string) {
  return prisma.user.findMany({
    where: {
      role: "STUDENT",
      status: "ACTIVE",
      courseEnrollments: { none: { courseId } },
    },
    orderBy: { fullName: "asc" },
    select: { id: true, fullName: true, username: true, gradeLevel: true },
  });
}

export interface CourseProjectRow {
  id: string;
  title: string;
  language: CodingLanguage;
  difficulty: CourseLevel;
  xpReward: number;
  status: PublishStatus;
  attemptCount: number;
  bestStatus: string | null;
}

/** Coding projects attached to a course. */
export async function listCourseProjects(
  scope: CourseScope,
  courseId: string
): Promise<CourseProjectRow[]> {
  const projects = await prisma.codingProject.findMany({
    where: {
      courseId,
      course: courseAccessFilter(scope),
      ...(scope.role === "STUDENT" ? { status: "PUBLISHED" as const } : {}),
    },
    orderBy: [{ orderIndex: "asc" }, { createdAt: "asc" }],
    select: {
      id: true,
      title: true,
      language: true,
      difficulty: true,
      xpReward: true,
      status: true,
      submissions: {
        where: { studentId: scope.userId },
        orderBy: { createdAt: "desc" },
        select: { status: true },
        take: 1,
      },
      _count: { select: { submissions: true } },
    },
  });

  return projects.map((project) => ({
    id: project.id,
    title: project.title,
    language: project.language,
    difficulty: project.difficulty,
    xpReward: project.xpReward,
    status: project.status,
    attemptCount: project._count.submissions,
    bestStatus: project.submissions[0]?.status ?? null,
  }));
}

/** Classroom rows for a given set of ids, used by the classes vertical. */
export async function listCoursesForClassroom(
  scope: CourseScope,
  classroomId: string
): Promise<CourseListItem[]> {
  return listCourses(scope, { classroomId });
}
