import { NextRequest, NextResponse } from "next/server";
import { Pool } from "pg";
import { requireAuth, getSession } from "@/lib/auth-utils";

const pool = new Pool({
  connectionString: process.env.DATABASE_URL,
});

// PATCH /api/settings/profile - Update current user's profile
export async function PATCH(request: NextRequest) {
  const { session, error } = await requireAuth();
  if (error) return error;

  try {
    const body = await request.json();
    const { name } = body;

    if (!name) {
      return NextResponse.json(
        { error: "Name is required" },
        { status: 400 }
      );
    }

    const result = await pool.query(
      `UPDATE "user" SET name = $1, "updatedAt" = NOW() WHERE id = $2
       RETURNING id, name, email`,
      [name, session!.user.id]
    );

    return NextResponse.json({ user: result.rows[0] });
  } catch (error) {
    console.error("Error updating profile:", error);
    return NextResponse.json(
      { error: "Failed to update profile" },
      { status: 500 }
    );
  }
}
