import { NextResponse } from 'next/server';
import { env } from '@/lib/env';

export async function POST(request: Request) {
  try {
    const { videoUrl } = await request.json();

    if (!videoUrl) {
      return NextResponse.json({ error: 'Video URL is required' }, { status: 400 });
    }

    const apiKey = env.transcriptApiKey;
    if (!apiKey) {
      return NextResponse.json({ error: 'Server configuration error: API key missing' }, { status: 500 });
    }

    const targetUrl = `https://transcriptapi.com/api/v2/youtube/search?q=${encodeURIComponent(videoUrl)}&type=video`;

    const response = await fetch(targetUrl, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json',
      },
    });

    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}));
      return NextResponse.json(
        { error: errorData.detail?.message || errorData.detail || 'Failed to fetch video data' },
        { status: response.status }
      );
    }

    const data = await response.json();
    const videoMeta = data.results?.[0];

    if (!videoMeta || !videoMeta.lengthText) {
      return NextResponse.json({ error: 'Video metadata or duration could not be found' }, { status: 404 });
    }

    const parseLengthToSeconds = (lengthStr: string): number => {
      const parts = lengthStr.split(':').map(Number);
      if (parts.length === 2) {
        return (parts[0] * 60) + parts[1]; // Format: MM:SS
      } else if (parts.length === 3) {
        return (parts[0] * 3600) + (parts[1] * 60) + parts[2]; // Format: HH:MM:SS
      }
      return 0;
    };

    return NextResponse.json({
      success: true,
      title: videoMeta.title,
      videoId: videoMeta.videoId,
      durationText: videoMeta.lengthText, // e.g., "12:34"
      durationSeconds: parseLengthToSeconds(videoMeta.lengthText), // e.g., 754
      hasCaptions: videoMeta.hasCaptions
    });

  } catch (error: any) {
    return NextResponse.json({ error: error.message }, { status: 500 });
  }
}
