import { linkDocument } from "@/app/actions/link-document";

export async function uploadAndLinkFiles(
  poId: string,
  files: File[],
  type: "po-document" | "receipt" = "po-document"
): Promise<{ error: string } | null> {
  for (const file of files) {
    const signRes = await fetch("/api/files/sign", {
      method: "POST",
      headers: { "Content-Type": "application/json" },
      body: JSON.stringify({ fileName: file.name, mimeType: file.type || "application/octet-stream", poId, type }),
    });
    if (!signRes.ok) return { error: `Failed to get upload URL for ${file.name}` };
    const { uploadUrl, key } = await signRes.json();

    const putRes = await fetch(uploadUrl, {
      method: "PUT",
      headers: { "Content-Type": file.type || "application/octet-stream" },
      body: file,
    });
    if (!putRes.ok) return { error: `Failed to upload ${file.name}` };

    const result = await linkDocument({
      poId,
      storageKey: key,
      fileName: file.name,
      fileSize: file.size,
      mimeType: file.type || "application/octet-stream",
    });
    if ("error" in result) return { error: result.error };
  }
  return null;
}
