import { NextResponse } from 'next/server';
import fs from 'fs';
import path from 'path';

export const dynamic = 'force-dynamic';

const MIME: Record<string, string> = {
  '.woff2': 'font/woff2',
  '.woff': 'font/woff',
  '.ttf': 'font/ttf',
  '.otf': 'font/otf',
};

const FONTS_DIR = path.join(process.cwd(), 'data', 'fonts');

function ensureFontsDir() {
  try { fs.mkdirSync(FONTS_DIR, { recursive: true }); } catch {}
}

export async function GET(request: Request) {
  const { searchParams } = new URL(request.url);
  const name = searchParams.get('name');

  if (name) {
    // Serve un singolo file font
    const safeName = path.basename(name); // protezione path traversal
    const ext = path.extname(safeName).toLowerCase();
    const mimeType = MIME[ext];
    if (!mimeType) return new NextResponse('Unsupported format', { status: 400 });

    const filePath = path.join(FONTS_DIR, safeName);
    try {
      const buffer = fs.readFileSync(filePath);
      return new NextResponse(buffer, {
        headers: {
          'Content-Type': mimeType,
          'Cache-Control': 'public, max-age=31536000, immutable',
          'Access-Control-Allow-Origin': '*',
        },
      });
    } catch {
      return new NextResponse('Font not found', { status: 404 });
    }
  }

  // List mode: ritorna i font "regular" (non-italic) presenti
  ensureFontsDir();
  try {
    const files = fs.readdirSync(FONTS_DIR);
    const list = files
      .filter(f => /\.(woff2?|ttf|otf)$/i.test(f))
      .filter(f => !/italic|bold/i.test(f))
      .sort();
    return NextResponse.json(list);
  } catch {
    return NextResponse.json([]);
  }
}
