import { adminForbidden, isAdminRequest } from "../../../lib/admin-auth";
import { ensureSchema, getUploadBucket, uid } from "../../../lib/mvp-db";

export async function POST(request: Request) {
  if (!(await isAdminRequest(request))) return adminForbidden();
  try {
    await ensureSchema();
    const form = await request.formData();
    const file = form.get("file");
    if (!(file instanceof File) || file.size === 0) {
      return Response.json({ error: "请选择示例截图" }, { status: 400 });
    }
    if (!file.type.startsWith("image/") || file.size > 8_000_000) {
      return Response.json({ error: "仅支持8MB以内的图片" }, { status: 400 });
    }
    const extension =
      file.name.split(".").at(-1)?.replace(/[^a-zA-Z0-9]/g, "") || "jpg";
    const key = `task-assets/${uid("example")}.${extension}`;
    await getUploadBucket().put(key, await file.arrayBuffer(), {
      httpMetadata: { contentType: file.type },
      customMetadata: { kind: "screenshot-task-example" },
    });
    return Response.json({ uploaded: true, key });
  } catch (error) {
    return Response.json(
      { error: error instanceof Error ? error.message : "示例截图上传失败" },
      { status: 500 },
    );
  }
}
