import { promises as fs } from 'node:fs';
import path from 'node:path';
import { NextResponse } from 'next/server';

export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';

export async function GET(_req: Request, ctx: { params: Promise<{ filename: string }> }) {
  const { filename } = await ctx.params;
  if (!filename.endsWith('.json') || filename.includes('..') || filename.includes('/')) {
    return NextResponse.json({ error: 'bad filename' }, { status: 400 });
  }

  try {
    const file = path.join(process.cwd(), 'data', 'exports', filename);
    const raw = await fs.readFile(file, 'utf-8');
    return new NextResponse(raw, {
      headers: {
        'Content-Type': 'application/json; charset=utf-8',
        'Content-Disposition': `attachment; filename="${filename}"`,
      },
    });
  } catch {
    return NextResponse.json({ error: 'not found' }, { status: 404 });
  }
}
