import feishuSnapshot from "../../../lib/feishu-source-snapshot.json";
import { adminForbidden, isAdminRequest } from "../../../lib/admin-auth";
import { ensureSchema, getUploadBucket } 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 sheetId = String(form.get("sheetId") ?? "").trim();
    const sourceRow = Number(form.get("sourceRow"));
    const imageIndex = Number(form.get("imageIndex"));
    const file = form.get("file");
    if (
      sheetId !== feishuSnapshot.sheetId ||
      !Number.isInteger(sourceRow) ||
      !Number.isInteger(imageIndex) ||
      !(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 row = feishuSnapshot.rows.find(
      (item) => item.sourceRow === sourceRow,
    );
    const asset = row?.images.find((item) => item.index === imageIndex);
    if (!asset) {
      return Response.json({ error: "图片不属于当前飞书内容表" }, { status: 422 });
    }
    await getUploadBucket().put(asset.key, await file.arrayBuffer(), {
      httpMetadata: { contentType: file.type },
      customMetadata: {
        sheetId,
        sourceRow: String(sourceRow),
        imageIndex: String(imageIndex),
      },
    });
    return Response.json({ uploaded: true });
  } catch (error) {
    return Response.json(
      { error: error instanceof Error ? error.message : "图片同步失败" },
      { status: 500 },
    );
  }
}
