import { NextResponse } from "next/server";
import { getDb, getCollection } from "@/lib/mongodb";

// Test MongoDB connection
export async function GET() {
  try {
    // Test database connection
    const db = await getDb();
    const dbName = db.databaseName;
    
    // List collections
    const collections = await db.listCollections().toArray();
    const collectionNames = collections.map(c => c.name);
    
    // Get document counts for each collection
    const collectionStats: { [key: string]: number } = {};
    for (const col of collections) {
      try {
        const count = await db.collection(col.name).countDocuments();
        collectionStats[col.name] = count;
      } catch (error) {
        collectionStats[col.name] = 0;
      }
    }
    
    // Test a query on users collection
    let userSample = null;
    try {
      const usersCollection = await getCollection("users");
      userSample = await usersCollection.findOne({});
    } catch (error) {
      // Collection might not exist, that's okay
    }
    
    return NextResponse.json({
      success: true,
      message: "Connected to MongoDB successfully",
      database: dbName,
      collections: collectionNames,
      collectionStats,
      userSample: userSample ? {
        _id: userSample._id?.toString(),
        email: userSample.email,
        name: userSample.name,
        role: userSample.role,
      } : null,
      timestamp: new Date().toISOString(),
    });
  } catch (error) {
    console.error("MongoDB connection test error:", error);
    return NextResponse.json(
      {
        success: false,
        error: "Failed to connect to MongoDB",
        details: error instanceof Error ? error.message : "Unknown error",
        timestamp: new Date().toISOString(),
      },
      { status: 500 }
    );
  }
}

