/**
 * Generate a long-lived MCP API key for ChatGPT integration
 */

import { NextResponse } from 'next/server';
import { getAdminAuth, getAdminDb } from '@/lib/firebase/admin';
import { randomBytes } from 'crypto';

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();
    const adminDb = getAdminDb();
    
    let userId: string;
    try {
      const decodedToken = await adminAuth.verifyIdToken(idToken);
      userId = decodedToken.uid;
    } catch (error) {
      return NextResponse.json({ error: 'Invalid token' }, { status: 401 });
    }

    // Check if user already has an MCP key
    const mcpKeysRef = adminDb.collection('mcpKeys');
    const existingKey = await mcpKeysRef
      .where('userId', '==', userId)
      .limit(1)
      .get();

    if (!existingKey.empty) {
      // Return existing key
      const keyDoc = existingKey.docs[0];
      const keyData = keyDoc.data();
      
      return NextResponse.json({
        apiKey: keyData.key,
        createdAt: keyData.createdAt,
        message: 'Using existing MCP API key',
      });
    }

    // Generate new API key
    const apiKey = `vibn_mcp_${randomBytes(32).toString('hex')}`;

    // Store in Firestore
    await mcpKeysRef.add({
      userId,
      key: apiKey,
      type: 'mcp',
      createdAt: new Date().toISOString(),
      lastUsed: null,
    });

    return NextResponse.json({
      apiKey,
      createdAt: new Date().toISOString(),
      message: 'MCP API key generated successfully',
    });
  } catch (error) {
    console.error('Error generating MCP key:', error);
    return NextResponse.json(
      {
        error: 'Failed to generate MCP key',
        details: error instanceof Error ? error.message : String(error),
      },
      { status: 500 }
    );
  }
}

// DELETE endpoint to revoke MCP key
export async function DELETE(request: Request) {
  try {
    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();
    const adminDb = getAdminDb();
    
    let userId: string;
    try {
      const decodedToken = await adminAuth.verifyIdToken(idToken);
      userId = decodedToken.uid;
    } catch (error) {
      return NextResponse.json({ error: 'Invalid token' }, { status: 401 });
    }

    // Delete user's MCP key
    const mcpKeysRef = adminDb.collection('mcpKeys');
    const existingKey = await mcpKeysRef
      .where('userId', '==', userId)
      .get();

    if (existingKey.empty) {
      return NextResponse.json({ message: 'No MCP key to delete' });
    }

    // Delete all keys for this user
    const batch = adminDb.batch();
    existingKey.docs.forEach(doc => {
      batch.delete(doc.ref);
    });
    await batch.commit();

    return NextResponse.json({ message: 'MCP key deleted successfully' });
  } catch (error) {
    console.error('Error deleting MCP key:', error);
    return NextResponse.json(
      {
        error: 'Failed to delete MCP key',
        details: error instanceof Error ? error.message : String(error),
      },
      { status: 500 }
    );
  }
}

