import { NextRequest, NextResponse } from "next/server";
import { auth } from "@/auth";
import { prisma } from "@/lib/db";

export async function GET() {
  const session = await auth();
  if (!session?.user?.id) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const user = await prisma.user.findUnique({
    where: { id: session.user.id },
    select: {
      id: true,
      email: true,
      displayName: true,
      avatarUrl: true,
      jobTitle: true,
      company: true,
      bio: true,
      hashedPassword: true,
    },
  });

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

  return NextResponse.json({
    id: user.id,
    email: user.email,
    displayName: user.displayName ?? "",
    avatarUrl: user.avatarUrl ?? "",
    jobTitle: user.jobTitle ?? "",
    company: user.company ?? "",
    bio: user.bio ?? "",
    hasPassword: !!user.hashedPassword,
  });
}

export async function PUT(req: NextRequest) {
  const session = await auth();
  if (!session?.user?.id) {
    return NextResponse.json({ error: "Unauthorized" }, { status: 401 });
  }

  const body = await req.json();
  const data: Record<string, string> = {};
  const allowedFields = ["displayName", "avatarUrl", "jobTitle", "company", "bio"];
  for (const field of allowedFields) {
    if (typeof body[field] === "string") data[field] = body[field];
  }

  const user = await prisma.user.update({
    where: { id: session.user.id },
    data,
    select: { id: true, displayName: true, avatarUrl: true, jobTitle: true, company: true, bio: true, email: true },
  });

  return NextResponse.json({ success: true, user });
}
