'use server';

import { auth } from "@/auth";
import { revalidatePath } from "next/cache";
import { createFileNode } from "@/data-access/file-nodes";
import { ensureOneDriveFolder, uploadLargeFile } from "@/services/onedrive";

export async function uploadFileAction(formData: FormData) {
  const session = await auth();
  if (!session?.user?.id) throw new Error("Unauthorized");

  const file = formData.get("file") as File;
  const folderName = "WebCalibre";

  try {
    // 1. Logic: Ensure destination exists
    await ensureOneDriveFolder(session.user.id, folderName);

    // 2. Logic: Perform the cloud upload
    const driveItem = await uploadLargeFile(session.user.id, file, folderName);

    // 3. Logic: Save the result to our DB
    await createFileNode({
      oneDriveId: driveItem.id,
      name: file.name,
      size: BigInt(file.size),
      isFolder: false,
      path: `/${folderName}/${file.name}`,
      ownerId: session.user.id,
      metadata: { 
        type: file.name.split('.').pop()?.toUpperCase(),
        mimeType: file.type 
      }
    });

    revalidatePath("/dashboard");
    return { success: true };
  } catch (error: any) {
    console.error("Upload Action Error:", error);
    return { success: false, error: error.message || "Upload failed" };
  }
}