import { NextRequest, NextResponse } from 'next/server';
import { downloadVideo } from '@/lib/youtube';
import { isValidYouTubeUrl } from '@/lib/utils';
import type { DownloadRequest } from '@/lib/types';

export async function POST(request: NextRequest) {
  try {
    const body: DownloadRequest = await request.json();
    
    if (!body.url || !body.format || !body.formatType) {
      return NextResponse.json(
        { success: false, error: 'Missing required fields' },
        { status: 400 }
      );
    }
    
    // Validate YouTube URL
    if (!isValidYouTubeUrl(body.url)) {
      return NextResponse.json(
        { success: false, error: 'Invalid YouTube URL' },
        { status: 400 }
      );
    }
    
    const result = await downloadVideo(body);
    
    if (!result.success) {
      return NextResponse.json(result, { status: 500 });
    }
    
    return NextResponse.json(result);
  } catch (error: any) {
    console.error('API error:', error);
    return NextResponse.json(
      { success: false, error: error.message || 'Internal server error' },
      { status: 500 }
    );
  }
}
