import { NextRequest, NextResponse } from 'next/server';
import { db } from '@/lib/db';
import { isValidEmail, isValidName, isValidPhone, sanitizeString, isValidId } from '@/lib/validation';
import { checkRateLimit, getRateLimitIdentifier, rateLimitError, RATE_LIMITS } from '@/lib/rate-limit';

export async function POST(request: NextRequest) {
  try {
    // Rate limit
    const identifier = `update-profile:${getRateLimitIdentifier(request)}`;
    const rateLimit = checkRateLimit(identifier, RATE_LIMITS.auth);
    if (!rateLimit.allowed) {
      return rateLimitError(rateLimit.resetTime);
    }

    const body = await request.json();
    const { userId, name, email, phone, avatar } = body;

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

    if (!isValidId(userId)) {
      return NextResponse.json(
        { error: 'Invalid user ID' },
        { status: 400 }
      );
    }

    // Build update data
    const updateData: Record<string, unknown> = {};

    if (name !== undefined) {
      if (!isValidName(name)) {
        return NextResponse.json(
          { error: 'Name must be between 1 and 100 characters' },
          { status: 400 }
        );
      }
      updateData.name = sanitizeString(name);
    }

    if (email !== undefined) {
      if (!isValidEmail(email)) {
        return NextResponse.json(
          { error: 'Invalid email format' },
          { status: 400 }
        );
      }
      const sanitizedEmail = sanitizeString(email);
      // Check if email is already taken by another user
      const existing = await db.user.findUnique({ where: { email: sanitizedEmail } });
      if (existing && existing.id !== userId) {
        return NextResponse.json(
          { error: 'Email is already taken by another account' },
          { status: 409 }
        );
      }
      updateData.email = sanitizedEmail;
    }

    if (phone !== undefined) {
      if (phone && !isValidPhone(phone)) {
        return NextResponse.json(
          { error: 'Invalid phone number format' },
          { status: 400 }
        );
      }
      updateData.phone = phone ? sanitizeString(phone) : null;
    }

    if (avatar !== undefined) {
      // Avatar can be an emoji, data URL, or URL - store as is
      // Limit size to prevent abuse
      if (typeof avatar === 'string' && avatar.length > 100000) {
        return NextResponse.json(
          { error: 'Avatar data is too large' },
          { status: 400 }
        );
      }
      updateData.avatar = avatar || null;
    }

    if (Object.keys(updateData).length === 0) {
      return NextResponse.json(
        { error: 'No fields to update' },
        { status: 400 }
      );
    }

    // Update user
    const updatedUser = await db.user.update({
      where: { id: userId },
      data: updateData,
      select: {
        id: true,
        name: true,
        email: true,
        phone: true,
        avatar: true,
        roles: true,
      },
    });

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