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(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

    const userEmail = session.user?.email;
    
    if (!userEmail) {
      return NextResponse.json(
        { error: 'User email not found' },
        { status: 401 }
      );
    }
    
    const user = await prisma.user.findUnique({
      where: { email: userEmail },
      include: {
        profile: {
          include: {
            country: true,
          },
        },
      },
    });

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

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

    const userWithProfile = {
      id: user.id,
      email: user.email,
      name: fullName,
      role: user.role,
      image: user.profile?.profileImage || user.image,
      provider: user.provider,
      profile: user.profile ? {
        firstName: user.profile.firstName,
        lastName: user.profile.lastName,
        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,
      } : null,
    };

    return NextResponse.json({ user: userWithProfile });
  } catch (error) {
    console.error('Error fetching user profile:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}

export async function PUT(request: NextRequest) {
  try {
    const session = await getServerSession(authOptions);
    
    if (!session?.user) {
      return NextResponse.json(
        { error: 'Unauthorized' },
        { status: 401 }
      );
    }

    const userEmail = session.user?.email;
    
    if (!userEmail) {
      return NextResponse.json(
        { error: 'User email not found in session' },
        { status: 400 }
      );
    }
    
    const body = await request.json();
    
    const { firstName, lastName, phone, city, address, bio, title } = body;

    // Check if profile exists
    let profile = await prisma.profile.findUnique({
      where: { userId: userEmail },
    });

    if (!profile) {
      // Create profile if it doesn't exist
      profile = await prisma.profile.create({
        data: {
          userId: userEmail,
          firstName: firstName || '',
          lastName: lastName || '',
          phone,
          city,
          address,
          bio,
          title,
          countryId: 'switzerland', // Default to Switzerland
        },
        include: {
          country: true,
        },
      });
    } else {
      // Update existing profile
      profile = await prisma.profile.update({
        where: { userId: userEmail },
        data: {
          firstName: firstName || profile.firstName,
          lastName: lastName || profile.lastName,
          phone: phone !== undefined ? phone : profile.phone,
          city: city !== undefined ? city : profile.city,
          address: address !== undefined ? address : profile.address,
          bio: bio !== undefined ? bio : profile.bio,
          title: title !== undefined ? title : profile.title,
        },
        include: {
          country: true,
        },
      });
    }

    const fullName = `${profile.firstName || ''} ${profile.lastName || ''}`.trim();

    return NextResponse.json({
      message: 'Profile updated successfully',
      user: {
        id: userEmail,
        name: fullName,
        profile,
      },
    });
  } catch (error) {
    console.error('Error updating user profile:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}