// Laedt ein Bild von einer externen URL herunter und speichert es lokal unter
// public/img/pexels-cache/<category>/<hash>.<ext>. Gibt den relativen Pfad
// zurueck (OHNE basePath-Praefix - das muss die aufrufende Komponente beim
// Rendern selbst voranstellen, analog zu lib/api-client.ts).
import { createHash } from 'crypto';
import { mkdir, writeFile, access } from 'fs/promises';
import path from 'path';

const CACHE_ROOT = path.join(process.cwd(), 'public', 'img', 'pexels-cache');
const PUBLIC_PREFIX = '/img/pexels-cache';

function extensionFromContentType(contentType: string | null): string {
  if (!contentType) return 'jpg';
  if (contentType.includes('png')) return 'png';
  if (contentType.includes('webp')) return 'webp';
  return 'jpg';
}

async function fileExists(filePath: string): Promise<boolean> {
  try {
    await access(filePath);
    return true;
  } catch {
    return false;
  }
}

// Laedt genau ein Bild herunter (falls noch nicht lokal vorhanden - Hash der
// Quell-URL verhindert Doppel-Downloads bei mehrfachem Pool-Refill derselben
// Kategorie) und liefert den lokalen, relativen Pfad zurueck.
export async function downloadAndCacheImage(sourceUrl: string, category: string): Promise<string | null> {
  try {
    const hash = createHash('sha1').update(sourceUrl).digest('hex').slice(0, 16);
    const categoryDir = path.join(CACHE_ROOT, category);

    const existingJpg = path.join(categoryDir, `${hash}.jpg`);
    if (await fileExists(existingJpg)) return `${PUBLIC_PREFIX}/${category}/${hash}.jpg`;

    const res = await fetch(sourceUrl);
    if (!res.ok) return null;

    const contentType = res.headers.get('content-type');
    const ext = extensionFromContentType(contentType);
    const buffer = Buffer.from(await res.arrayBuffer());

    await mkdir(categoryDir, { recursive: true });
    const filename = `${hash}.${ext}`;
    await writeFile(path.join(categoryDir, filename), buffer);

    return `${PUBLIC_PREFIX}/${category}/${filename}`;
  } catch (e) {
    console.error('Bild-Download fehlgeschlagen:', sourceUrl, e);
    return null;
  }
}
