import { readFile } from 'fs/promises';
import path from 'path';
import sharp from 'sharp';
import { NextRequest, NextResponse } from 'next/server';

const VALID_SIZES = [192, 512] as const;

export async function GET(
  _request: NextRequest,
  { params }: { params: Promise<{ size: string }> },
) {
  const { size: sizeParam } = await params;
  const size = parseInt(sizeParam, 10);

  if (!VALID_SIZES.includes(size as (typeof VALID_SIZES)[number])) {
    return new NextResponse('Invalid size', { status: 400 });
  }

  try {
    const svgPath = path.join(process.cwd(), 'public', 'icon0.svg');
    const svgBuffer = await readFile(svgPath);
    const pngBuffer = await sharp(svgBuffer).resize(size, size).png().toBuffer();

    return new NextResponse(new Uint8Array(pngBuffer), {
      headers: {
        'Content-Type': 'image/png',
        'Cache-Control': 'public, max-age=31536000, immutable',
      },
    });
  } catch (error) {
    console.error('Error generating PWA icon:', error);
    return new NextResponse('Failed to generate icon', { status: 500 });
  }
}
