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,
  { params }: { params: Promise<{ clerk_id: string }> }
) {
  try {
    await connectDB();

    // params is a Promise in Next.js 15
    const { clerk_id: clerkId } = await params;

    // Validate clerk_id parameter
    if (!clerkId || clerkId.trim() === '') {
      return NextResponse.json(
        {
          success: false,
          error: 'Clerk ID is required',
        },
        { status: 400 }
      );
    }

    // 1. Try to find user in MongoDB
    let user = await User.findOne({ clerkId }).lean();

    // 2. If not found in MongoDB, try to fetch from Clerk and sync (Self-Healing)
    if (!user) {
      try {
        const client = await clerkClient();
        const clerkUser = await client.users.getUser(clerkId);

        if (clerkUser) {
          console.log(`User ${clerkId} not found in DB, syncing from Clerk...`);

          user = await User.create({
            clerkId: clerkUser.id,
            email: clerkUser.emailAddresses[0]?.emailAddress || '',
            name: clerkUser.firstName && clerkUser.lastName
              ? `${clerkUser.firstName} ${clerkUser.lastName}`
              : clerkUser.firstName || clerkUser.lastName || null,
            phone: clerkUser.phoneNumbers[0]?.phoneNumber || null,
            role: (clerkUser.publicMetadata?.role as string) || 'user',
            createdAt: new Date(),
            updatedAt: new Date(),
          });

          console.log('User auto-created from Clerk data');
        }
      } catch (clerkError) {
        console.error('Error fetching/syncing from Clerk:', clerkError);
        // Fallthrough - if we can't sync, we still return 404 below
      }
    }

    // Return 404 if user still not found
    if (!user) {
      return NextResponse.json(
        {
          success: false,
          error: 'User not found',
        },
        { status: 404 }
      );
    }

    // Return user object
    return NextResponse.json(
      {
        success: true,
        data: user,
      },
      { status: 200 }
    );
  } catch (error) {
    console.error('GET user by Clerk ID error:', error);
    return NextResponse.json(
      {
        success: false,
        error: 'Internal server error: ' + (error instanceof Error ? error.message : 'Unknown error'),
      },
      { status: 500 }
    );
  }
}