import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireRole } from "@/lib/auth";

type Params = { params: Promise<{ id: string }> };

const MAX_BYTES = 400 * 1024; // ~400 KB after client-side downscale

/** Set (POST { photoUrl: dataURL }) or remove (DELETE) a student's profile photo. */
export async function POST(req: Request, { params }: Params) {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { id } = await params;
  const student = await prisma.student.findFirst({
    where: { id: Number(id), institutionId: session.institutionId },
    select: { id: true },
  });
  if (!student) return NextResponse.json({ error: "Not found" }, { status: 404 });

  try {
    const body = await req.json();
    const photoUrl = typeof body.photoUrl === "string" ? body.photoUrl : "";
    const match = /^data:image\/(jpeg|png|webp);base64,([A-Za-z0-9+/=]+)$/.exec(photoUrl);
    if (!match) {
      return NextResponse.json({ error: "Invalid image" }, { status: 400 });
    }
    if (Buffer.from(match[2], "base64").length > MAX_BYTES) {
      return NextResponse.json({ error: "Image too large" }, { status: 400 });
    }

    await prisma.student.update({
      where: { id: student.id },
      data: { photoUrl },
    });
    return NextResponse.json({ success: true });
  } catch {
    return NextResponse.json({ error: "Could not save photo" }, { status: 500 });
  }
}

export async function DELETE(_req: Request, { params }: Params) {
  const session = await requireRole("INSTITUTION_ADMIN");
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const { id } = await params;
  const student = await prisma.student.findFirst({
    where: { id: Number(id), institutionId: session.institutionId },
    select: { id: true },
  });
  if (!student) return NextResponse.json({ error: "Not found" }, { status: 404 });

  await prisma.student.update({
    where: { id: student.id },
    data: { photoUrl: null },
  });
  return NextResponse.json({ success: true });
}
