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

export async function GET() {
  try {
    // Test 1: Check if Firebase Admin is initialized
    if (!adminDb) {
      return NextResponse.json(
        { error: 'Firebase Admin not initialized' },
        { status: 500 }
      );
    }

    // Test 2: Try to access Firestore (this will verify credentials)
    const testCollection = adminDb.collection('_healthcheck');
    const timestamp = new Date().toISOString();
    
    // Write a test document
    const docRef = await testCollection.add({
      message: 'Firebase connection test',
      timestamp: timestamp,
    });

    // Read it back
    const doc = await docRef.get();
    const data = doc.data();

    // Clean up
    await docRef.delete();

    // Test 3: Check Auth is working
    const authCheck = adminAuth ? 'OK' : 'Failed';

    return NextResponse.json({
      success: true,
      message: 'Firebase is connected successfully! 🎉',
      tests: {
        adminInit: 'OK',
        firestoreWrite: 'OK',
        firestoreRead: 'OK',
        authInit: authCheck,
      },
      projectId: process.env.FIREBASE_PROJECT_ID,
      testData: data,
    });
  } catch (error) {
    console.error('Firebase test error:', error);
    return NextResponse.json(
      {
        error: 'Firebase connection failed',
        details: error instanceof Error ? error.message : String(error),
        tip: 'Check your .env.local file for correct FIREBASE_PROJECT_ID, FIREBASE_CLIENT_EMAIL, and FIREBASE_PRIVATE_KEY',
      },
      { status: 500 }
    );
  }
}

