import { NextResponse } from 'next/server';
import { recordEvent } from '@/lib/auditDb';
import { generateSeedanceVideo } from '@/lib/videoProviders';
import type { VideoGenerationRequest } from '@/lib/types';

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

export async function POST(req: Request) {
  const body = (await req.json()) as VideoGenerationRequest;
  try {
    recordEvent({ action: 'video.generate_started', targetType: 'video', status: 'started', provider: 'seedance', metadata: { ratio: body.ratio, duration: body.duration, hasImage: Boolean(body.imageUrl), refs: body.references?.length ?? 0 } });
    const response = await generateSeedanceVideo(body);
    recordEvent({ action: 'video.generate_submitted', targetType: 'video', targetId: response.taskId ?? response.status, status: 'queued', provider: 'seedance', metadata: { status: response.status } });
    return NextResponse.json(response);
  } catch (error) {
    const message = String(error);
    recordEvent({ action: 'video.generate_failed', targetType: 'video', status: 'error', provider: 'seedance', message });
    return NextResponse.json({ error: message }, {
      status: message.includes('SEEDANCE_API_KEY missing') ? 503 : 500,
    });
  }
}
