import { NextRequest, NextResponse } from 'next/server';
import { getServerSession } from 'next-auth';
import { authOptions } from '@/lib/auth';
import { prisma } from '@/lib/prisma';

export async function GET(request: NextRequest) {
  try {
    const session = await getServerSession(authOptions);
    
    if (!session?.user) {
      return NextResponse.json(
        { session: null },
        { status: 200 }
      );
    }

    const userEmail = session.user?.email;
    
    if (!userEmail) {
      return NextResponse.json(
        { session: null },
        { status: 401 }
      );
    }
    
    // Fetch the complete user data with profile to ensure we have the latest name
    const user = await prisma.user.findUnique({
      where: { email: userEmail },
      include: {
        profile: true,
      },
    });

    if (!user) {
      return NextResponse.json(
        { session: null },
        { status: 200 }
      );
    }

    // Construct full name from profile data
    const fullName = user.profile 
      ? `${user.profile.firstName || ''} ${user.profile.lastName || ''}`.trim()
      : user.email?.split('@')[0] || 'User';

    // Return enhanced session with complete user data
    const enhancedSession = {
      ...session,
      user: {
        ...session.user,
        id: user.id,
        name: fullName || session.user.name, // Use profile name or fallback to session name
        email: user.email,
        image: user.profile?.profileImage || user.image || session.user.image,
        role: user.role,
        profile: user.profile ? {
          firstName: user.profile.firstName,
          lastName: user.profile.lastName,
          phone: user.profile.phone,
          city: user.profile.city,
          title: user.profile.title,
          profileImage: user.profile.profileImage,
        } : null,
      },
    };

    return NextResponse.json(enhancedSession);
  } catch (error) {
    console.error('Error fetching session with user data:', error);
    return NextResponse.json(
      { session: null, error: 'Internal server error' },
      { status: 500 }
    );
  }
}