import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { sanitizeString } from '@/lib/validation';

export async function GET(request: NextRequest) {
  try {
    const { searchParams } = new URL(request.url);
    const userId = searchParams.get('userId');

    if (!userId) {
      return NextResponse.json(
        { error: 'User ID is required' },
        { status: 400 }
      );
    }

    const user = await db.user.findUnique({ where: { id: userId } });
    if (!user) {
      return NextResponse.json(
        { error: 'User not found' },
        { status: 404 }
      );
    }

    const { password: _password, ...userWithoutPassword } = user;
    const userResponse = {
      ...userWithoutPassword,
      roles: userWithoutPassword.roles
        ? userWithoutPassword.roles.split(',').map((r: string) => r.trim())
        : ['general'],
    };

    return NextResponse.json({ user: userResponse }, { status: 200 });
  } catch (error) {
    console.error('Profile fetch error:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}

export async function PATCH(request: NextRequest) {
  try {
    const body = await request.json();
    const { userId, name, phone, bio, address, division, district, upazila, avatar, socialLinks } = body;

    if (!userId) {
      return NextResponse.json(
        { error: 'User ID is required' },
        { status: 400 }
      );
    }

    // Check if user exists
    const existingUser = await db.user.findUnique({ where: { id: userId } });
    if (!existingUser) {
      return NextResponse.json(
        { error: 'User not found' },
        { status: 404 }
      );
    }

    // Build update data with only provided fields
    const updateData: Record<string, string | null> = {};
    if (name !== undefined) updateData.name = sanitizeString(name);
    if (phone !== undefined) updateData.phone = phone ? sanitizeString(phone) : null;
    if (bio !== undefined) updateData.bio = bio ? sanitizeString(bio) : null;
    if (address !== undefined) updateData.address = address ? sanitizeString(address) : null;
    if (division !== undefined) updateData.division = division ? sanitizeString(division) : null;
    if (district !== undefined) updateData.district = district ? sanitizeString(district) : null;
    if (upazila !== undefined) updateData.upazila = upazila ? sanitizeString(upazila) : null;
    if (avatar !== undefined) updateData.avatar = avatar ? sanitizeString(avatar) : null;
    if (socialLinks !== undefined) updateData.socialLinks = socialLinks ? sanitizeString(socialLinks) : null;

    const updatedUser = await db.user.update({
      where: { id: userId },
      data: updateData,
    });

    const { password: _password, ...userWithoutPassword } = updatedUser;
    // Convert roles string to array for client consumption
    const userResponse = {
      ...userWithoutPassword,
      roles: userWithoutPassword.roles
        ? userWithoutPassword.roles.split(',').map((r: string) => r.trim())
        : ['general'],
    };

    return NextResponse.json(
      { user: userResponse, message: 'Profile updated successfully' },
      { status: 200 }
    );
  } catch (error) {
    console.error('Profile update error:', error);
    return NextResponse.json(
      { error: 'Internal server error' },
      { status: 500 }
    );
  }
}
