import { NextResponse, type NextRequest } from "next/server";
import { prisma } from "@/lib/db";
import { getSessionUser, type SessionUser } from "@/lib/auth/session";
import { readLocalFile } from "@/lib/storage";
import { env } from "@/lib/env";

/**
 * Whether `key` is referenced as an attachment by an assignment or lesson the
 * caller is allowed to see.
 *
 * Reuses the same ownership rules the rest of the app uses: staff see material
 * for courses they own (directly or through the classroom), students see it for
 * courses they are enrolled in. Admins see everything.
 */
async function canReadStoredKey(user: SessionUser, key: string): Promise<boolean> {
  if (user.role === "ADMIN") return true;

  const courseScope =
    user.role === "TEACHER"
      ? { OR: [{ teacherId: user.id }, { classroom: { teacherId: user.id } }] }
      : {
          OR: [
            { enrollments: { some: { studentId: user.id, status: "ACTIVE" as const } } },
            { classroom: { enrollments: { some: { studentId: user.id, status: "ACTIVE" as const } } } },
          ],
        };

  const [lesson, assignment] = await Promise.all([
    prisma.lesson.findFirst({
      where: { attachmentUrl: key, course: courseScope },
      select: { id: true },
    }),
    prisma.assignment.findFirst({
      where: { attachmentUrl: key, course: courseScope },
      select: { id: true },
    }),
  ]);

  return Boolean(lesson || assignment);
}

/**
 * Serve a stored upload.
 *
 * Two addressing modes, both authorized:
 *   • `/api/files/<submissionId>` — a submission attachment. The caller must be
 *     the submitting student, or staff who manage that course.
 *   • `/api/files/<storageKey>`    — an assignment or lesson attachment. The key
 *     is only served when it is actually referenced by material the caller is
 *     allowed to see (own course as teacher, enrolled course as student).
 *
 * Authorization is checked before any bytes are read, so a guessed id cannot
 * leak another student's work.
 *
 * A trailing `/download` segment is accepted and ignored, and every link the app
 * generates includes it. The shared host in front of this app (DomaiNesia)
 * answers any request whose final path segment carries a file extension —
 * `.txt`, `.pdf`, `.png`, `.zip`, `.docx`, … — with its own 404, and never
 * forwards it to Next.js. A storage key almost always ends in one of those
 * extensions, so without the extra segment every attachment download 404s at
 * the edge before this handler ever runs. Verified against the live host: the
 * bare key is intercepted, the same key with `/download` appended reaches here.
 */
export async function GET(
  _request: NextRequest,
  { params }: { params: Promise<{ key: string[] }> }
) {
  const user = await getSessionUser();
  if (!user) {
    return NextResponse.json({ error: "Tidak terautentikasi." }, { status: 401 });
  }

  const { key } = await params;
  // Drop the trailing `/download` marker described above.
  const segments = key.length > 1 && key[key.length - 1] === "download" ? key.slice(0, -1) : key;
  const joined = segments.join("/");
  if (!joined) {
    return NextResponse.json({ error: "Berkas tidak ditemukan." }, { status: 404 });
  }

  // Try the submission-attachment mode first.
  const submission = await prisma.submission.findUnique({
    where: { id: joined },
    select: {
      studentId: true,
      fileUrl: true,
      fileName: true,
      assignment: {
        select: {
          course: {
            select: { teacherId: true, classroom: { select: { teacherId: true } } },
          },
        },
      },
    },
  });

  let storageKey: string | null = null;
  let downloadName: string | null = null;

  if (submission?.fileUrl) {
    const ownerIds = [
      submission.assignment.course.teacherId,
      submission.assignment.course.classroom?.teacherId,
    ].filter(Boolean) as string[];

    const allowed =
      user.role === "ADMIN" ||
      user.id === submission.studentId ||
      (user.role === "TEACHER" && ownerIds.includes(user.id));

    if (!allowed) {
      return NextResponse.json({ error: "Tidak diizinkan." }, { status: 403 });
    }

    storageKey = submission.fileUrl;
    downloadName = submission.fileName;
  } else {
    // Raw-key mode. The key is not a secret — it appears in the page source of
    // every lesson and assignment that uses it — so serving any key to any
    // authenticated account let a student in one class read every other
    // course's material by copying a key out of an id they had seen. The key
    // must be referenced by material the caller can actually reach.
    if (!(await canReadStoredKey(user, joined))) {
      return NextResponse.json({ error: "Tidak diizinkan." }, { status: 403 });
    }
    storageKey = joined;
  }

  const buffer = await readLocalFile(storageKey);
  if (!buffer) {
    // S3 keys are not readable through this route.
    if (env.STORAGE_DRIVER === "s3") {
      return NextResponse.json(
        { error: "Berkas ini disimpan di object storage." },
        { status: 404 }
      );
    }
    return NextResponse.json({ error: "Berkas tidak ditemukan." }, { status: 404 });
  }

  const name = downloadName ?? storageKey.split("/").pop() ?? "berkas";

  return new NextResponse(new Uint8Array(buffer), {
    headers: {
      "Content-Type": "application/octet-stream",
      "Content-Disposition": `attachment; filename="${encodeURIComponent(name)}"`,
      "Cache-Control": "private, max-age=0, must-revalidate",
    },
  });
}
