/**
 * Retrieve ChatGPT GPT information
 * Note: This is limited by what's available via OpenAI API
 * GPTs are primarily accessible through the ChatGPT web interface
 */

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

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 { gptUrl } = await request.json();

    if (!gptUrl) {
      return NextResponse.json({ error: 'GPT URL is required' }, { status: 400 });
    }

    // Extract GPT ID from URL
    // Format: https://chatgpt.com/g/g-p-[id]-[name]/project
    const gptMatch = gptUrl.match(/\/g\/(g-p-[a-zA-Z0-9]+)/);
    
    if (!gptMatch) {
      return NextResponse.json({ error: 'Invalid GPT URL format' }, { status: 400 });
    }

    const gptId = gptMatch[1];
    const nameMatch = gptUrl.match(/g-p-[a-zA-Z0-9]+-([^\/]+)/);
    const gptName = nameMatch ? nameMatch[1].replace(/-/g, ' ') : 'Unknown GPT';

    console.log(`[ChatGPT GPT] Extracted ID: ${gptId}, Name: ${gptName}`);

    // Note: OpenAI API doesn't currently expose GPTs directly
    // We'll store the reference for now and display in the UI
    return NextResponse.json({
      success: true,
      data: {
        id: gptId,
        name: gptName,
        url: gptUrl,
        type: 'chatgpt-gpt',
        message: 'GPT reference saved. To capture conversations with this GPT, import individual chat sessions.',
      },
    });
  } catch (error) {
    console.error('[ChatGPT GPT] Error:', error);
    return NextResponse.json(
      {
        error: 'Failed to process GPT',
        details: error instanceof Error ? error.message : String(error),
      },
      { status: 500 }
    );
  }
}

