import { NextResponse } from 'next/server';
import { adminAuth, adminDb } from '@/lib/firebase/admin';
import { v4 as uuidv4 } from 'uuid';
import { FieldValue } from 'firebase-admin/firestore';

export async function GET(request: Request) {
  try {
    console.log('[API] Getting API key...');
    
    // Get the authorization header
    const authHeader = request.headers.get('authorization');
    if (!authHeader?.startsWith('Bearer ')) {
      console.error('[API] No authorization header');
      return NextResponse.json(
        { error: 'No authorization token provided' },
        { status: 401 }
      );
    }

    const token = authHeader.substring(7);
    console.log('[API] Token received, verifying...');
    
    // Verify the Firebase ID token
    const decodedToken = await adminAuth.verifyIdToken(token);
    const userId = decodedToken.uid;
    console.log('[API] Token verified, userId:', userId);

    // Check if user already has an API key
    console.log('[API] Checking for existing API key...');
    const userDoc = await adminDb.collection('users').doc(userId).get();
    
    if (userDoc.exists && userDoc.data()?.apiKey) {
      console.log('[API] Found existing API key');
      return NextResponse.json({
        apiKey: userDoc.data()!.apiKey,
      });
    }

    // Generate new API key
    console.log('[API] Generating new API key...');
    const apiKey = `vibn_${uuidv4().replace(/-/g, '')}`;
    
    // Store API key document
    console.log('[API] Storing API key in Firestore...');
    await adminDb.collection('apiKeys').doc(apiKey).set({
      key: apiKey,
      userId,
      createdAt: FieldValue.serverTimestamp(),
      isActive: true,
    });
    
    // Update user document with API key reference (or create if doesn't exist)
    console.log('[API] Updating user document...');
    await adminDb.collection('users').doc(userId).set({
      apiKey,
      updatedAt: FieldValue.serverTimestamp(),
    }, { merge: true });

    console.log('[API] API key created successfully:', apiKey);
    return NextResponse.json({
      apiKey,
      isNew: true,
    });
  } catch (error) {
    console.error('[API] Error getting/creating API key:', error);
    console.error('[API] Error stack:', error instanceof Error ? error.stack : 'No stack trace');
    return NextResponse.json(
      {
        error: 'Failed to get API key',
        details: error instanceof Error ? error.message : String(error),
      },
      { status: 500 }
    );
  }
}

