import fs from 'node:fs';
import { prisma } from '@/lib/db';
import { currentUser } from '@/lib/auth';
import { signedUrl, localPath } from '@/lib/storage';
export const dynamic = 'force-dynamic';

export async function GET(req: Request, { params }: { params: Promise<{ id: string }> }) {
  const u = await currentUser(); if (!u) return new Response('Giriş gerekli', { status: 401 });
  const { id } = await params;
  const o = await prisma.order.findUnique({ where: { id } });
  if (!o || (o.userId !== u.id && u.role !== 'ADMIN')) return new Response('Bulunamadı', { status: 404 });
  const which = new URL(req.url).searchParams.get('f') === 'poster' ? 'poster' : 'video';
  const key = which === 'poster' ? o.posterKey : o.videoKey;
  if (!key) { if (which === 'video' && o.videoUrl) return Response.redirect(o.videoUrl, 302); return new Response('Henüz hazır değil', { status: 404 }); }
  const name = `${o.code}-${o.ada}-${o.parsel}.${which === 'poster' ? 'jpg' : 'mp4'}`;
  const s = await signedUrl(key, new URL(req.url).searchParams.has('dl') ? name : undefined);
  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 type = which === 'poster' ? 'image/jpeg' : 'video/mp4';
  const range = req.headers.get('range');
  const headers: Record<string, string> = { 'Content-Type': type, 'Accept-Ranges': 'bytes' };
  if (new URL(req.url).searchParams.has('dl')) headers['Content-Disposition'] = `attachment; filename="${name}"`;
  if (range) {
    const [s0, e0] = range.replace('bytes=', '').split('-');
    const start = Number(s0), end = e0 ? Number(e0) : stat.size - 1;
    const stream = fs.createReadStream(p, { start, end });
    return new Response(stream 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) } });
}
