/**
 * Retrieve OpenAI Projects using the Projects API
 * https://platform.openai.com/docs/api-reference/projects
 */

import { NextResponse } from 'next/server';
import { getAdminAuth } from '@/lib/firebase/admin';

const OPENAI_API_URL = 'https://api.openai.com/v1/projects';

export async function POST(request: Request) {
  try {
    // Authenticate user
    const authHeader = request.headers.get('Authorization');
    if (!authHeader?.startsWith('Bearer ')) {
      return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
    }

    const idToken = authHeader.split('Bearer ')[1];
    const adminAuth = getAdminAuth();
    
    let userId: string;
    try {
      const decodedToken = await adminAuth.verifyIdToken(idToken);
      userId = decodedToken.uid;
    } catch (error) {
      return NextResponse.json({ error: 'Invalid token' }, { status: 401 });
    }

    const { openaiApiKey, projectId } = await request.json();

    if (!openaiApiKey) {
      return NextResponse.json({ error: 'OpenAI API key is required' }, { status: 400 });
    }

    // If projectId provided, fetch specific project
    const url = projectId 
      ? `${OPENAI_API_URL}/${projectId}`
      : OPENAI_API_URL; // List all projects

    console.log(`[OpenAI Projects] Fetching: ${url}`);
    
    const openaiResponse = await fetch(url, {
      method: 'GET',
      headers: {
        'Authorization': `Bearer ${openaiApiKey}`,
        'Content-Type': 'application/json',
      },
    });

    if (!openaiResponse.ok) {
      const errorText = await openaiResponse.text();
      console.error('[OpenAI Projects] API error:', openaiResponse.status, errorText);
      return NextResponse.json(
        { 
          error: 'Failed to fetch from OpenAI',
          details: errorText,
          status: openaiResponse.status,
        },
        { status: openaiResponse.status }
      );
    }

    const projectData = await openaiResponse.json();
    console.log('[OpenAI Projects] Data fetched successfully');

    return NextResponse.json({
      success: true,
      data: projectData,
    });
  } catch (error) {
    console.error('[OpenAI Projects] Error:', error);
    return NextResponse.json(
      {
        error: 'Failed to fetch OpenAI project',
        details: error instanceof Error ? error.message : String(error),
      },
      { status: 500 }
    );
  }
}

