import "server-only";
import { prisma } from "@/lib/db";
import type { Role } from "@prisma/client";
import { listCourses } from "@/lib/queries/courses";
import { listAssignments } from "@/lib/queries/assignments";
import { listCodingProjects } from "@/lib/queries/coding";

/**
 * Global search across the workspace.
 *
 * Reuses the same list queries the individual pages use, so a result can never
 * appear here for a record the actor is not allowed to open. Each source is
 * capped before being merged.
 */

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

export interface SearchHit {
  id: string;
  kind: "course" | "assignment" | "project" | "lesson";
  title: string;
  meta: string | null;
  href: string;
}

export interface SearchResults {
  query: string;
  hits: SearchHit[];
  counts: { courses: number; assignments: number; projects: number; lessons: number };
}

const PER_SOURCE = 12;

export async function searchWorkspace(
  scope: SearchScope,
  rawQuery: string
): Promise<SearchResults> {
  const query = rawQuery.trim();
  if (query.length < 2) {
    return {
      query,
      hits: [],
      counts: { courses: 0, assignments: 0, projects: 0, lessons: 0 },
    };
  }

  const [courses, assignments, projects, lessons] = await Promise.all([
    listCourses(scope, { search: query }),
    listAssignments(scope, { search: query }),
    listCodingProjects(scope),
    searchLessons(scope, query),
  ]);

  const courseHits: SearchHit[] = courses.slice(0, PER_SOURCE).map((course) => ({
    id: course.id,
    kind: "course",
    title: course.title,
    meta: course.summary,
    href: `/dashboard/courses/${course.id}`,
  }));

  const assignmentHits: SearchHit[] = assignments.slice(0, PER_SOURCE).map((assignment) => ({
    id: assignment.id,
    kind: "assignment",
    title: assignment.title,
    meta: assignment.courseTitle,
    href: `/dashboard/assignments/${assignment.id}`,
  }));

  // Coding projects have no server-side text filter, so match on the fields a
  // reader would search by and cap the result here.
  const needle = query.toLowerCase();
  const projectHits: SearchHit[] = projects
    .filter(
      (project) =>
        project.title.toLowerCase().includes(needle) ||
        project.description.toLowerCase().includes(needle)
    )
    .slice(0, PER_SOURCE)
    .map((project) => ({
      id: project.id,
      kind: "project",
      title: project.title,
      meta: project.courseTitle ?? null,
      href: `/dashboard/coding/${project.id}`,
    }));

  const lessonHits: SearchHit[] = lessons.map((lesson) => ({
    id: lesson.id,
    kind: "lesson",
    title: lesson.title,
    meta: lesson.courseTitle,
    href: `/dashboard/lessons/${lesson.id}`,
  }));

  return {
    query,
    hits: [...courseHits, ...lessonHits, ...assignmentHits, ...projectHits],
    counts: {
      courses: courseHits.length,
      lessons: lessonHits.length,
      assignments: assignmentHits.length,
      projects: projectHits.length,
    },
  };
}

/** Lessons are searched by title within the courses the actor may read. */
interface LessonSearchHit {
  id: string;
  title: string;
  courseTitle: string;
  courseId: string;
  href: string;
}

async function searchLessons(
  scope: SearchScope,
  query: string
): Promise<LessonSearchHit[]> {
  const lessons = await prisma.lesson.findMany({
    where: {
      AND: [
        { title: { contains: query, mode: "insensitive" } },
        scope.role === "STUDENT" ? { status: "PUBLISHED" as const } : {},
        scope.role === "STUDENT"
          ? {
              course: {
                OR: [
                  { enrollments: { some: { studentId: scope.userId } } },
                  {
                    classroom: {
                      enrollments: {
                        some: { studentId: scope.userId, status: "ACTIVE" as const },
                      },
                    },
                  },
                ],
              },
            }
          : scope.role === "TEACHER"
            ? {
                course: {
                  OR: [
                    { teacherId: scope.userId },
                    { classroom: { teacherId: scope.userId } },
                  ],
                },
              }
            : {},
      ],
    },
    orderBy: [{ orderIndex: "asc" }],
    take: PER_SOURCE,
    select: {
      id: true,
      title: true,
      course: { select: { id: true, title: true } },
    },
  });

  return lessons.map((lesson) => ({
    id: lesson.id,
    title: lesson.title,
    courseTitle: lesson.course.title,
    courseId: lesson.course.id,
    href: `/dashboard/lessons/${lesson.id}`,
  }));
}
