import { NextResponse } from 'next/server';
import { prisma } from '../../../lib/prisma';
import { requireAuth } from '../../../lib/jwt';
import { hashPassword } from '../../../lib/auth';

export async function PATCH(req: Request) {
  try {
    const session = await requireAuth(req);
    const body = await req.json();

    const name = body.name !== undefined && body.name !== null ? String(body.name).trim() : undefined;
    const phone = body.phone !== undefined && body.phone !== null ? String(body.phone).trim() : undefined;
    const password = body.password ? String(body.password) : undefined;

    if (name === undefined && phone === undefined && !password) {
      return NextResponse.json({ error: 'No updates provided' }, { status: 400 });
    }

    const data: any = {};
    if (name !== undefined) data.name = name || null;
    if (phone !== undefined) data.phone = phone || null;
    if (password) {
      if (password.length < 8) {
        return NextResponse.json({ error: 'Password must be at least 8 characters' }, { status: 400 });
      }
      data.passwordHash = await hashPassword(password);
    }

    const user = await prisma.user.update({
      where: { id: session.userId },
      data,
      select: { id: true, email: true, name: true, phone: true, role: true, status: true, emailVerifiedAt: true, approvedAt: true },
    });

    return NextResponse.json({ ok: true, user });
  } catch (error) {
    console.error('Profile update error', error);
    return NextResponse.json({ error: 'Failed to update profile' }, { status: 500 });
  }
}
export const dynamic = 'force-dynamic';
