import { Font } from '@/src/lib/typography';
import { NextRequest } from 'next/server';
import { createResponse, handleApiError } from '@/src/lib/api';

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const term = searchParams.get('search');
    const API_KEY = process.env.GOOGLE_FONTS_API_KEY;
    const resp = await fetch(`https://www.googleapis.com/webfonts/v1/webfonts?key=${API_KEY}&sort=popularity`);
    if (!resp.ok) {
      return createResponse(resp.status, 'Failed to fetch fonts');
    }
    const data = await resp.json();
    const fonts = data.items
      .filter((font: Font) => font.family.toLowerCase().includes(term?.toLowerCase() ?? ''))
      .map((font: Font) => ({
        label: font.family,
        value: font.family,
        variants: font.variants,
      }));
    return createResponse(200, 'Fonts fetched successfully', { data: fonts });
  } catch (error) {
    return handleApiError(error);
  }
}
