"use server";

import { auth } from "@/auth";
import { db } from "@/lib/db";
import { revalidatePath } from "next/cache";

export async function linkDocument({
  poId,
  storageKey,
  fileName,
  fileSize,
  mimeType,
}: {
  poId: string;
  storageKey: string;
  fileName: string;
  fileSize: number;
  mimeType: string;
}): Promise<{ ok: true } | { error: string }> {
  const session = await auth();
  if (!session?.user) return { error: "Unauthorized" };

  const po = await db.purchaseOrder.findUnique({ where: { id: poId }, select: { id: true } });
  if (!po) return { error: "PO not found" };

  await db.pODocument.create({
    data: { poId, storageKey, fileName, fileSize, mimeType },
  });

  revalidatePath(`/po/${poId}`);
  return { ok: true };
}
