// src/app/dashboard/sync-actions.ts
'use server';

import { auth } from "@/auth";
import { revalidatePath } from "next/cache";
import { upsertFileNode } from "@/data-access/file-nodes";
import { getWebCalibreChildren } from "@/services/onedrive";
import { extractMetadata } from "@/lib/metadata-extractor"; // Import your utility

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

  try {
    const items = await getWebCalibreChildren(session.user.id);
    
    let syncedCount = 0;
    const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;

    for (const item of items) {
      const isFolder = !!item.folder;

      if (isFolder && uuidRegex.test(item.name)) continue;

      const extension = isFolder ? 'FOLDER' : (item.name.split('.').pop()?.toLowerCase() || 'unknown');
      
      let deepMetadata = {};

      // --- NEW: Extraction Logic ---
      // Only extract for specific types to save time/bandwidth
      const supportedTypes = ['pdf', 'epub', 'jpg', 'jpeg', 'png', 'webp'];
      
      if (!isFolder && supportedTypes.includes(extension)) {
        const downloadUrl = item['@microsoft.graph.downloadUrl'];
        
        if (downloadUrl) {
          try {
            // Fetch the file content as an ArrayBuffer
            const response = await fetch(downloadUrl);
            const arrayBuffer = await response.arrayBuffer();
            const buffer = Buffer.from(arrayBuffer);

            // Extract the "deep" metadata (Author, Title, etc.)
            deepMetadata = await extractMetadata(buffer, item.name);
          } catch (extractError) {
            console.error(`Could not extract metadata for ${item.name}:`, extractError);
          }
        }
      }

      // 2. Save to database with combined metadata
      await upsertFileNode(item.id, {
        name: item.name,
        size: BigInt(item.size || 0),
        isFolder: isFolder,
        path: item.parentReference?.path + '/' + item.name,
        ownerId: session.user.id,
        metadata: { 
          type: extension.toUpperCase(), 
          mimeType: item.file?.mimeType || null,
          ...deepMetadata // Merge the extracted Author, Title, etc.
        },
      });
      
      syncedCount++;
    }
    
    revalidatePath('/dashboard');
    return { success: true, count: syncedCount };
  } catch (error: any) {
    console.error("Sync Error:", error.message);
    throw new Error("Failed to sync with OneDrive");
  }
}