/**
 * GET /api/auth/me
 *
 * Exposes a profile endpoint for the VibnCode desktop app.
 * Resolves the Bearer vibn_sk_... Workspace API key, queries the database,
 * and returns the corresponding owner's user details.
 */

import { NextResponse } from "next/server";
import { requireWorkspacePrincipal } from "@/lib/auth/workspace-auth";
import { queryOne } from "@/lib/db-postgres";

export async function GET(request: Request) {
  // 1. Authenticate the Workspace API key or Browser Session
  const principal = await requireWorkspacePrincipal(request);
  if (principal instanceof NextResponse) return principal;

  try {
    // 2. Query user details from fs_users
    const user = await queryOne<{
      id: string;
      data: any;
    }>(
      `SELECT id, data FROM fs_users WHERE id = $1 LIMIT 1`,
      [principal.userId]
    );

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

    // 3. Return user profile compatible with the desktop client's User expectations
    return NextResponse.json({
      user: {
        id: user.id,
        name: user.data?.name || user.data?.display_name || "Vibn Owner",
        email: user.data?.email || "",
        photoUrl: user.data?.image || user.data?.photo_url || null,
        workspace: principal.workspace.slug,
      }
    });
  } catch (err) {
    console.error("[api/auth/me GET]", err);
    return NextResponse.json({ error: "Failed to resolve profile" }, { status: 500 });
  }
}
