import { NextResponse } from "next/server";
import { putBinaryFile, getFile } from "@/lib/github";

function checkAdmin(request) {
  const token = request.headers.get("x-admin-token");
  return token && token === process.env.ADMIN_PASSWORD;
}

/** POST /api/github/upload
 *  Body: multipart form with fields: path (string), file (File)
 */
export async function POST(request) {
  if (!checkAdmin(request)) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const formData = await request.formData();
  const path = formData.get("path");
  const file = formData.get("file");

  if (!path || !file) {
    return NextResponse.json(
      { error: "path and file required" },
      { status: 400 },
    );
  }

  // Convert file to base64
  const arrayBuffer = await file.arrayBuffer();
  const base64 = Buffer.from(arrayBuffer).toString("base64");

  // Check if file already exists to get sha (needed for update)
  let sha;
  try {
    const existing = await getFile(path);
    sha = existing.sha;
  } catch {
    sha = undefined; // new file
  }

  try {
    const result = await putBinaryFile(
      path,
      base64,
      sha,
      `Upload ${file.name}`,
    );
    return NextResponse.json(result);
  } catch (err) {
    return NextResponse.json({ error: err.message }, { status: 500 });
  }
}