import 'server-only';
import fs from 'node:fs/promises';
import path from 'node:path';
import crypto from 'node:crypto';

const DIR = path.join(process.cwd(), 'public', 'uploads');
const MAX_BYTES = 6 * 1024 * 1024;
const EXT: Record<string, string> = {
  'image/jpeg': 'jpg',
  'image/png': 'png',
  'image/webp': 'webp',
  'image/gif': 'gif',
};

export async function saveImage(file: File): Promise<string | null> {
  if (!file || typeof file.arrayBuffer !== 'function' || file.size === 0) return null;
  const ext = EXT[file.type];
  if (!ext || file.size > MAX_BYTES) return null;
  await fs.mkdir(DIR, { recursive: true });
  const name = crypto.randomBytes(12).toString('hex') + '.' + ext;
  await fs.writeFile(path.join(DIR, name), Buffer.from(await file.arrayBuffer()));
  return '/uploads/' + name;
}

export async function saveImages(files: File[], max = 8): Promise<string[]> {
  const out: string[] = [];
  for (const f of files.slice(0, max)) {
    const p = await saveImage(f);
    if (p) out.push(p);
  }
  return out;
}
