import { NextResponse } from 'next/server';
import { adminAuth, adminDb } from '@/lib/firebase/admin';

export async function GET(request: Request) {
  const diagnostics: any = {
    timestamp: new Date().toISOString(),
    environment: {},
    firebase: {},
    token: {},
  };

  try {
    // Check environment variables
    diagnostics.environment = {
      FIREBASE_PROJECT_ID: process.env.FIREBASE_PROJECT_ID ? 'SET' : 'NOT SET',
      FIREBASE_CLIENT_EMAIL: process.env.FIREBASE_CLIENT_EMAIL ? 'SET' : 'NOT SET',
      FIREBASE_PRIVATE_KEY: process.env.FIREBASE_PRIVATE_KEY ? `SET (${process.env.FIREBASE_PRIVATE_KEY.length} chars)` : 'NOT SET',
      NEXT_PUBLIC_FIREBASE_PROJECT_ID: process.env.NEXT_PUBLIC_FIREBASE_PROJECT_ID || 'NOT SET',
    };

    // Test Firebase Admin
    try {
      const testDoc = await adminDb.collection('test').doc('diagnostic').get();
      diagnostics.firebase.adminDb = 'OK - Can access Firestore';
      diagnostics.firebase.adminAuth = 'OK - Auth service initialized';
    } catch (error: any) {
      diagnostics.firebase.error = error.message;
    }

    // Try to verify a token if provided
    const authHeader = request.headers.get('authorization');
    if (authHeader?.startsWith('Bearer ')) {
      const token = authHeader.substring(7);
      diagnostics.token.received = true;
      diagnostics.token.length = token.length;
      
      try {
        const decodedToken = await adminAuth.verifyIdToken(token);
        diagnostics.token.verification = 'SUCCESS';
        diagnostics.token.uid = decodedToken.uid;
        diagnostics.token.email = decodedToken.email;
      } catch (error: any) {
        diagnostics.token.verification = 'FAILED';
        diagnostics.token.error = error.message;
        diagnostics.token.errorCode = error.code;
      }
    } else {
      diagnostics.token.received = false;
      diagnostics.token.note = 'No token provided - add Authorization: Bearer <token> header to test';
    }

    return NextResponse.json(diagnostics, { status: 200 });
  } catch (error: any) {
    diagnostics.criticalError = {
      message: error.message,
      stack: error.stack,
    };
    return NextResponse.json(diagnostics, { status: 500 });
  }
}

