import { NextResponse } from "next/server";

export const runtime = "nodejs";

interface RemoveBgBody {
  image?: string;
}

export async function POST(request: Request) {
  const apiKey = process.env.REMOVE_BG_API_KEY;
  const rembgUrl = process.env.REMBG_SERVICE_URL;

  let body: RemoveBgBody;
  try {
    body = (await request.json()) as RemoveBgBody;
  } catch {
    return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
  }

  if (!body.image?.startsWith("data:image")) {
    return NextResponse.json({ error: "image data URL required" }, { status: 400 });
  }

  const base64 = body.image.split(",")[1];
  if (!base64) {
    return NextResponse.json({ error: "Invalid data URL" }, { status: 400 });
  }

  const buffer = Buffer.from(base64, "base64");

  if (rembgUrl) {
    try {
      const response = await fetch(rembgUrl, {
        method: "POST",
        headers: { "Content-Type": "application/octet-stream" },
        body: buffer,
      });
      if (!response.ok) {
        return NextResponse.json(
          { error: "rembg service failed" },
          { status: 502 }
        );
      }
      const resultBuffer = Buffer.from(await response.arrayBuffer());
      return NextResponse.json({
        image: `data:image/png;base64,${resultBuffer.toString("base64")}`,
      });
    } catch {
      return NextResponse.json(
        { error: "Could not reach rembg service" },
        { status: 502 }
      );
    }
  }

  if (!apiKey) {
    return NextResponse.json(
      {
        error:
          "Background removal not configured. Set REMOVE_BG_API_KEY or REMBG_SERVICE_URL.",
      },
      { status: 503 }
    );
  }

  const formData = new FormData();
  formData.append(
    "image_file",
    new Blob([buffer], { type: "image/png" }),
    "upload.png"
  );
  formData.append("size", "auto");

  const response = await fetch("https://api.remove.bg/v1.0/removebg", {
    method: "POST",
    headers: { "X-Api-Key": apiKey },
    body: formData,
  });

  if (!response.ok) {
    return NextResponse.json(
      { error: "remove.bg API request failed" },
      { status: response.status }
    );
  }

  const resultBuffer = Buffer.from(await response.arrayBuffer());
  return NextResponse.json({
    image: `data:image/png;base64,${resultBuffer.toString("base64")}`,
  });
}
