'use server';

// src/app/update/[id]/_actions.ts

import { auth } from "@/auth";
import { revalidatePath } from "next/cache";
import { getFileNodeById, updateFileNode } from "@/data-access/file-nodes";

/**
 * SERVER ACTION: Updates file metadata and organizational data.
 */
export async function updateFileAction(formData: FormData) {
  const session = await auth();
  
  // 1. Authorization Guard
  if (!session?.user?.id) {
    return { success: false, message: "Unauthorized" };
  }

  // 2. Data Extraction from FormData
  const id = formData.get("id") as string;
  const name = formData.get("name") as string;
  const description = formData.get("description") as string;
  const parentIdRaw = formData.get("parentId") as string;
  const customMetadataRaw = formData.get("customMetadata") as string;

  const parentId = (parentIdRaw === "" || parentIdRaw === "root") ? null : parentIdRaw;
  
  try {
    // 3. Parse the incoming metadata from the UI
    const newMetadata = customMetadataRaw ? JSON.parse(customMetadataRaw) : {};

    // 4. DAL: Fetch existing record to safely merge system fields
    const existing = await getFileNodeById(id);
    if (!existing) throw new Error("File record not found");
    if (existing.ownerId !== session.user.id) throw new Error("Permission denied");

    const existingMetadata = (existing.metadata as Record<string, any>) || {};

    // 5. Logic: Merge Strategy
    // We keep internal system fields like 'mimeType' but allow the 
    // user-approved 'newMetadata' (including extracted GPS/Author) to take precedence.
    const updatedMetadata = {
      ...existingMetadata, // Keep everything we currently have
      ...newMetadata,      // Overwrite with the fields the user just approved/edited
    };

    // 6. DAL: Perform the update via your file-nodes logic
    await updateFileNode(id, {
      name: name || existing.name,
      description,
      parentId,
      metadata: updatedMetadata,
    });

    // 7. Cache Invalidation
    revalidatePath("/dashboard");
    revalidatePath(`/update/${id}`);
    
    return { success: true };
  } catch (error: any) {
    console.error("Update action error:", error);
    return { 
      success: false, 
      message: error.message || "An unexpected error occurred during update" 
    };
  }
}