import fs from 'node:fs';
import { signedUrl, localPath } from '@/lib/storage';
/** Depolamadaki dosyayı (yerel veya S3) aralık isteği destekli sunar. */
export async function serveKey(req: Request, key: string, type: string, downloadName?: string) {
  const s = await signedUrl(key, downloadName);
  if (s) return Response.redirect(s, 302);
  const p = localPath(key);
  if (!fs.existsSync(p)) return new Response('Dosya yok', { status: 404 });
  const stat = fs.statSync(p);
  const headers: Record<string, string> = { 'Content-Type': type, 'Accept-Ranges': 'bytes', 'Cache-Control': 'private, max-age=300' };
  if (downloadName) headers['Content-Disposition'] = `attachment; filename="${downloadName}"`;
  const range = req.headers.get('range');
  if (range) {
    const [s0, e0] = range.replace('bytes=', '').split('-');
    const start = Number(s0), end = e0 ? Math.min(Number(e0), stat.size - 1) : stat.size - 1;
    return new Response(fs.createReadStream(p, { start, end }) as unknown as ReadableStream, { status: 206, headers: { ...headers, 'Content-Range': `bytes ${start}-${end}/${stat.size}`, 'Content-Length': String(end - start + 1) } });
  }
  return new Response(fs.createReadStream(p) as unknown as ReadableStream, { headers: { ...headers, 'Content-Length': String(stat.size) } });
}
