import { NextResponse } from "next/server";
import { prisma } from "@/lib/prisma";
import { requireAnyRole, STAFF_SIDE_ROLES } from "@/lib/auth";

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

/** The caller's own signature image (POST { signatureUrl: dataURL } to set,
    DELETE to remove) — printed on result sheets/certificates they sign. */
export async function POST(req: Request) {
  const session = await requireAnyRole([...STAFF_SIDE_ROLES]);
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const me = await prisma.user.findUnique({
    where: { id: session.userId },
    select: { staffId: true },
  });
  if (!me?.staffId) return NextResponse.json({ error: "FORBIDDEN" }, { status: 403 });

  try {
    const body = await req.json();
    const signatureUrl = typeof body.signatureUrl === "string" ? body.signatureUrl : "";
    const match = /^data:image\/(jpeg|png|webp);base64,([A-Za-z0-9+/=]+)$/.exec(signatureUrl);
    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.staff.update({
      where: { id: me.staffId },
      data: { signatureUrl },
    });
    return NextResponse.json({ success: true });
  } catch {
    return NextResponse.json({ error: "Could not save signature" }, { status: 500 });
  }
}

export async function DELETE() {
  const session = await requireAnyRole([...STAFF_SIDE_ROLES]);
  if (!session || !session.institutionId) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const me = await prisma.user.findUnique({
    where: { id: session.userId },
    select: { staffId: true },
  });
  if (!me?.staffId) return NextResponse.json({ error: "FORBIDDEN" }, { status: 403 });

  await prisma.staff.update({
    where: { id: me.staffId },
    data: { signatureUrl: null },
  });
  return NextResponse.json({ success: true });
}
