import { writeFile, mkdir } from 'fs/promises';
import path from 'path';

/**
 * Uploads a file to the local public/uploads directory.
 * Returns the public relative URL to be saved in the database.
 */
export async function uploadFileLocally(file: File): Promise<string> {
  const bytes = await file.arrayBuffer();
  const buffer = Buffer.from(bytes);

  const uploadDir = path.join(process.cwd(), 'public', 'uploads');
  
  // Create directory if it doesn't exist
  try {
    await mkdir(uploadDir, { recursive: true });
  } catch (e) {
    // Directory already exists, ignore
  }

  const uniqueName = `${Date.now()}-${file.name.replace(/[^a-zA-Z0-9.-]/g, "_")}`;
  const filePath = path.join(uploadDir, uniqueName);
  
  await writeFile(filePath, buffer);

  // Return the path relative to the public directory so Next.js can serve it
  return `/uploads/${uniqueName}`;
}
