import { NextRequest, NextResponse } from 'next/server';
import { prisma } from '@/lib/prisma';

export async function GET(request: NextRequest) {
  try {
    // Get all users with their profile information
    const allUsers = await prisma.user.findMany({
      include: {
        profile: {
          include: {
            country: true,
          },
        },
      },
      orderBy: {
        createdAt: 'desc',
      },
    });

    // Separate users with and without profiles
    const usersWithProfiles = allUsers.filter(user => user.profile !== null);
    const usersWithoutProfiles = allUsers.filter(user => user.profile === null);

    // Get detailed statistics
    const stats = {
      totalUsers: allUsers.length,
      usersWithProfiles: usersWithProfiles.length,
      usersWithoutProfiles: usersWithoutProfiles.length,
      percentageWithoutProfiles: allUsers.length > 0 
        ? ((usersWithoutProfiles.length / allUsers.length) * 100).toFixed(2) 
        : 0,
    };

    // Format user data for better readability
    const formatUserData = (users: typeof allUsers) => {
      return users.map(user => ({
        id: user.id,
        email: user.email,
        role: user.role,
        provider: user.provider,
        emailVerified: user.emailVerified,
        image: user.image,
        createdAt: user.createdAt,
        profile: user.profile ? {
          id: user.profile.id,
          firstName: user.profile.firstName,
          lastName: user.profile.lastName,
          fullName: `${user.profile.firstName || ''} ${user.profile.lastName || ''}`.trim(),
          phone: user.profile.phone,
          city: user.profile.city,
          address: user.profile.address,
          bio: user.profile.bio,
          title: user.profile.title,
          profileImage: user.profile.profileImage,
          country: user.profile.country ? {
            id: user.profile.country.id,
            name: user.profile.country.name,
            code: user.profile.country.code,
          } : null,
          createdAt: user.profile.createdAt,
          updatedAt: user.profile.updatedAt,
        } : null,
      }));
    };

    // Get a sample of users for detailed analysis
    const sampleUsersWithProfiles = formatUserData(usersWithProfiles.slice(0, 5));
    const sampleUsersWithoutProfiles = formatUserData(usersWithoutProfiles.slice(0, 5));

    // Check for potential issues
    const issues = [];
    
    if (usersWithoutProfiles.length > 0) {
      issues.push(`${usersWithoutProfiles.length} users found without profiles`);
    }

    // Check for users with incomplete profiles
    const incompleteProfiles = usersWithProfiles.filter(user => {
      const profile = user.profile!;
      return !profile.firstName || !profile.lastName || !profile.phone;
    });

    if (incompleteProfiles.length > 0) {
      issues.push(`${incompleteProfiles.length} users have incomplete profiles (missing name or phone)`);
    }

    // Check for users without email verification
    const unverifiedUsers = allUsers.filter(user => !user.emailVerified);
    if (unverifiedUsers.length > 0) {
      issues.push(`${unverifiedUsers.length} users have unverified emails`);
    }

    // Analysis for session display names
    const sessionNameAnalysis = allUsers.map(user => {
      let displayName = 'Unknown User';
      
      if (user.profile && (user.profile.firstName || user.profile.lastName)) {
        displayName = `${user.profile.firstName || ''} ${user.profile.lastName || ''}`.trim();
      } else if (user.email) {
        displayName = user.email.split('@')[0];
      }
      
      return {
        userId: user.id,
        email: user.email,
        hasProfile: !!user.profile,
        displayName,
        nameSource: user.profile && (user.profile.firstName || user.profile.lastName) 
          ? 'profile' 
          : 'email',
      };
    });

    const usersWithEmailNames = sessionNameAnalysis.filter(u => u.nameSource === 'email');

    return NextResponse.json({
      success: true,
      timestamp: new Date().toISOString(),
      statistics: stats,
      issues: issues.length > 0 ? issues : ['No issues found'],
      sessionNameAnalysis: {
        totalUsers: sessionNameAnalysis.length,
        usersUsingEmailAsName: usersWithEmailNames.length,
        usersUsingProfileName: sessionNameAnalysis.length - usersWithEmailNames.length,
        sampleEmailBasedNames: usersWithEmailNames.slice(0, 3).map(u => ({
          email: u.email,
          displayName: u.displayName,
        })),
      },
      data: {
        usersWithoutProfiles: {
          count: usersWithoutProfiles.length,
          sample: sampleUsersWithoutProfiles,
        },
        usersWithProfiles: {
          count: usersWithProfiles.length,
          sample: sampleUsersWithProfiles,
        },
        incompleteProfiles: {
          count: incompleteProfiles.length,
          users: incompleteProfiles.slice(0, 3).map(user => ({
            id: user.id,
            email: user.email,
            firstName: user.profile?.firstName,
            lastName: user.profile?.lastName,
            phone: user.profile?.phone,
          })),
        },
      },
      recommendations: [
        usersWithoutProfiles.length > 0 
          ? 'Create profiles for users without them to ensure proper session display names'
          : 'All users have profiles',
        incompleteProfiles.length > 0
          ? 'Encourage users with incomplete profiles to fill in their names'
          : 'All profiles are complete',
        unverifiedUsers.length > 0
          ? 'Send email verification reminders to unverified users'
          : 'All users have verified emails',
      ],
    });

  } catch (error) {
    console.error('Database diagnostic error:', error);
    return NextResponse.json(
      { 
        success: false,
        message: 'Database diagnostic failed',
        error: error instanceof Error ? error.message : 'Unknown error',
        timestamp: new Date().toISOString(),
      },
      { status: 500 }
    );
  }
}