import { NextRequest, NextResponse } from 'next/server';

export const dynamic = 'force-dynamic';

const HEYGEN_API_KEY = process.env.HEYGEN_API_KEY || '';

export async function GET(request: NextRequest) {
  const { searchParams } = new URL(request.url);
  const videoId = searchParams.get('id');

  if (!videoId) {
    return NextResponse.json({ error: 'Missing video ID' }, { status: 400 });
  }

  try {
    const res = await fetch(
      `https://api.heygen.com/v1/video_status.get?video_id=${videoId}`,
      { headers: { 'X-Api-Key': HEYGEN_API_KEY }, cache: 'no-store' }
    );
    const data = await res.json();
    const d = data?.data || {};

    return NextResponse.json({
      status: d.status || 'unknown',
      video_url: d.video_url || null,
      thumbnail_url: d.thumbnail_url || null,
      duration: d.duration || null,
    });
  } catch (err) {
    console.error('HeyGen video fetch error:', err);
    return NextResponse.json({ error: 'Failed to fetch video status' }, { status: 500 });
  }
}
