import { prisma } from '@/lib/db';
import { agentGuard } from '@/lib/agentRoute';
import { putObject } from '@/lib/storage';
import { sendEmail } from '@/lib/notify';
import { apLong } from '@/lib/ap';
/**
 * Teslim: multipart/form-data (video: mp4, poster?: jpg, durationSec?) veya JSON { videoUrl, durationSec }.
 * Multipart'ta imza gövdenin ham baytları üzerinden hesaplanır.
 */
export async function POST(req: Request, { params }: { params: Promise<{ id: string }> }) {
  const bad = await agentGuard(req); if (bad) return bad;
  const { id } = await params;
  const o = await prisma.order.findUnique({ where: { id }, include: { user: true } });
  if (!o) return Response.json({ error: 'Bulunamadı' }, { status: 404 });
  const ct = req.headers.get('content-type') || '';
  const data: { videoKey?: string; posterKey?: string; videoUrl?: string; durationSec?: number } = {};
  if (ct.includes('multipart/form-data')) {
    const fd = await req.formData();
    const v = fd.get('video'); if (!(v instanceof File)) return Response.json({ error: 'video alanı gerekli' }, { status: 400 });
    data.videoKey = await putObject(`orders/${o.id}/${o.code}.mp4`, Buffer.from(await v.arrayBuffer()), 'video/mp4');
    const p = fd.get('poster'); if (p instanceof File) data.posterKey = await putObject(`orders/${o.id}/${o.code}.jpg`, Buffer.from(await p.arrayBuffer()), 'image/jpeg');
    if (fd.get('durationSec')) data.durationSec = Number(fd.get('durationSec'));
  } else {
    const b = await req.json();
    if (!b.videoUrl || !/^https:\/\//.test(b.videoUrl)) return Response.json({ error: 'videoUrl (https) gerekli' }, { status: 400 });
    data.videoUrl = b.videoUrl; if (b.durationSec) data.durationSec = Number(b.durationSec);
  }
  await prisma.order.update({ where: { id }, data: { ...data, status: 'DELIVERED', progress: 100, progressMsg: 'Teslim edildi', deliveredAt: new Date(), error: null } });
  await prisma.job.updateMany({ where: { orderId: id, status: { in: ['queued', 'external', 'running'] } }, data: { status: 'done' } });
  await sendEmail(o.user.email, `Videonuz hazır: ${apLong(o.ada, o.parsel)}`, `<p>Merhaba ${o.user.name},</p><p>${o.mahalle} ${apLong(o.ada, o.parsel)} videonuz hazır. Panelinizden izleyip indirebilirsiniz.</p>`);
  return Response.json({ ok: true });
}
