import { NextResponse } from 'next/server';
import { readImageFile, type ImageBucket } from '@/lib/storage';

export const runtime = 'nodejs';

export async function GET(_req: Request, ctx: { params: Promise<{ bucket: string; filename: string }> }) {
  const { bucket, filename } = await ctx.params;
  if (!['generated', 'selected', 'refs', 'packs', 'anchors', 'uploads'].includes(bucket)) {
    return NextResponse.json({ error: 'bad bucket' }, { status: 400 });
  }
  if (filename.includes('..') || filename.includes('/')) {
    return NextResponse.json({ error: 'bad filename' }, { status: 400 });
  }
  const r = await readImageFile(bucket as ImageBucket, filename);
  if (!r) return NextResponse.json({ error: 'not found' }, { status: 404 });
  return new NextResponse(new Uint8Array(r.buf), {
    headers: { 'Content-Type': r.type, 'Cache-Control': 'public, max-age=31536000, immutable' },
  });
}
