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

export const runtime = 'nodejs';

export const TTS_AUDIO_DIR = path.join(process.cwd(), '.tts-temp');

export async function GET(
  _req: NextRequest,
  { params }: { params: Promise<{ filename: string }> }
): Promise<NextResponse> {
  const { filename } = await params;

  const safeFilename = path.basename(filename);
  if (!safeFilename.endsWith('.wav') || safeFilename !== filename) {
    return new NextResponse(null, { status: 404 });
  }

  const filePath = path.join(TTS_AUDIO_DIR, safeFilename);

  let fileBuffer: Buffer;
  try {
    fileBuffer = fs.readFileSync(filePath);
  } catch {
    return new NextResponse(null, { status: 404 });
  }

  try {
    fs.unlinkSync(filePath);
  } catch {
    /* already deleted by concurrent request or session cleanup — ignore */
  }

  return new NextResponse(new Uint8Array(fileBuffer), {
    headers: {
      'Content-Type': 'audio/wav',
      'Content-Length': String(fileBuffer.length),
      'Cache-Control': 'no-store',
    },
  });
}
