import { NextRequest, NextResponse } from 'next/server';
import { connectDB } from '@/lib/mongodb';
import User from '@/models/User';
import { clerkClient } from '@clerk/nextjs/server';

export async function GET(request: NextRequest) {
    try {
        const search = request.nextUrl.searchParams.get('search');

        if (!search) {
            return NextResponse.json({ error: 'Please provide ?search=email_or_id' }, { status: 400 });
        }

        await connectDB();
        const client = await clerkClient();

        // 1. Find in DB
        const dbUsers = await User.find({
            $or: [
                { email: { $regex: search, $options: 'i' } },
                { name: { $regex: search, $options: 'i' } },
                { clerkId: search }
            ]
        }).lean();

        // 2. Find in Clerk
        const clerkUsersResponse = await client.users.getUserList({
            query: search,
            limit: 5
        });

        // Also try to find by ID if search looks like an ID
        let clerkUserById = null;
        if (search.startsWith('user_')) {
            try {
                clerkUserById = await client.users.getUser(search);
            } catch (e) { }
        }

        const clerkUsers = [...(clerkUsersResponse.data || [])];
        if (clerkUserById && !clerkUsers.find(u => u.id === clerkUserById?.id)) {
            clerkUsers.push(clerkUserById);
        }

        // 3. Compare
        const comparison = {
            dbResults: dbUsers,
            clerkResults: clerkUsers.map(u => ({
                id: u.id,
                email: u.emailAddresses[0]?.emailAddress,
                publicMetadata: u.publicMetadata,
                privateMetadata: u.privateMetadata,
                createdAt: u.createdAt,
                updatedAt: u.updatedAt
            }))
        };

        return NextResponse.json({
            success: true,
            env: {
                clerkPublishableKeyPrefix: process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY?.substring(0, 8),
                clerkSecretKeyPrefix: process.env.CLERK_SECRET_KEY?.substring(0, 8),
                isDevMode: process.env.NEXT_PUBLIC_CLERK_PUBLISHABLE_KEY?.startsWith('pk_test_')
            },
            data: comparison
        });

    } catch (error) {
        return NextResponse.json(
            { error: 'Internal server error: ' + (error instanceof Error ? error.message : 'Unknown error') },
            { status: 500 }
        );
    }
}
