import { NextRequest, NextResponse } from 'next/server';
import { getVideoInfo } from '@/lib/youtube';
import { isValidYouTubeUrl } from '@/lib/utils';

export async function POST(request: NextRequest) {
  try {
    const body = await request.json();
    const { url } = body;
    
    if (!url) {
      return NextResponse.json(
        { success: false, error: 'URL is required' },
        { status: 400 }
      );
    }
    
    // Validate YouTube URL
    if (!isValidYouTubeUrl(url)) {
      return NextResponse.json(
        { success: false, error: 'Invalid YouTube URL' },
        { status: 400 }
      );
    }
    
    const videoInfo = await getVideoInfo(url);
    
    if (!videoInfo) {
      return NextResponse.json(
        { success: false, error: 'Failed to get video info' },
        { status: 500 }
      );
    }
    
    return NextResponse.json({ success: true, videoInfo });
  } catch (error: any) {
    console.error('API error:', error);
    return NextResponse.json(
      { success: false, error: error.message || 'Internal server error' },
      { status: 500 }
    );
  }
}
