import { NextResponse } from 'next/server';
import { recordEvent } from '@/lib/auditDb';
import { getSeedanceVideoTask } from '@/lib/videoProviders';
import { loadSession, saveRemoteVideo, saveSession } from '@/lib/storage';

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

export async function GET(req: Request, ctx: { params: Promise<{ taskId: string }> }) {
  const { taskId } = await ctx.params;
  const sessionId = new URL(req.url).searchParams.get('sessionId')?.trim();
  try {
    const response = await getSeedanceVideoTask(taskId);
    let task = undefined;
    let videoUrl = response.videoUrl;

    if (sessionId) {
      const session = await loadSession(sessionId);
      if (session?.videoTasks?.length) {
        const index = session.videoTasks.findIndex(item => item.taskId === taskId);
        if (index >= 0) {
          if (videoUrl) {
            videoUrl = await saveRemoteVideo(session.id, taskId, videoUrl);
          }
          task = {
            ...session.videoTasks[index],
            status: response.status,
            videoUrl: videoUrl ?? session.videoTasks[index].videoUrl,
            model: response.model,
            updatedAt: Date.now(),
            raw: response.raw,
          };
          session.videoTasks = [
            ...session.videoTasks.slice(0, index),
            task,
            ...session.videoTasks.slice(index + 1),
          ];
          await saveSession(session);
        }
      }
    }

    recordEvent({ action: 'video.status_checked', sessionId, targetType: 'video', targetId: taskId, status: 'ok', provider: 'seedance', metadata: { status: response.status } });
    return NextResponse.json({ ...response, videoUrl, task });
  } catch (error) {
    const message = String(error);
    recordEvent({ action: 'video.status_failed', sessionId, targetType: 'video', targetId: taskId, status: 'error', provider: 'seedance', message });
    return NextResponse.json({ error: message }, {
      status: message.includes('SEEDANCE_API_KEY missing') ? 503 : 500,
    });
  }
}
