import type { GetCurrentUserResponse } from "@/types/proto/api/v1/auth_service_pb";
import { fetchJson } from "./apiClient";

// Clerk is the source of truth for authentication.
// This client is now only used to fetch the "current user" view
// backed by Clerk JWT on the backend.
export const authServiceClient = {
  async getCurrentUser(_request?: unknown): Promise<GetCurrentUserResponse> {
    void _request;
    const data = await fetchJson<unknown>("/auth/me", { method: "GET" });

    // Support both response formats:
    // 1) Connect/proto: { user: {...} }
    // 2) Legacy REST: {...user fields...}
    if (data && typeof data === "object" && "user" in data) {
      return data as GetCurrentUserResponse;
    }

    if (data && typeof data === "object") {
      const legacyUser = data as Record<string, unknown>;
      const id = String(legacyUser.id ?? "");
      const username = String(legacyUser.username ?? "");
      const email = String(legacyUser.email ?? "");
      const name = String(legacyUser.name ?? (id ? `users/${id}` : ""));

      return {
        user: {
          name,
          role: 1,
          username,
          email,
          displayName: String(legacyUser.displayName ?? username),
          avatarUrl: String(legacyUser.avatarUrl ?? ""),
          description: String(legacyUser.description ?? ""),
          password: "",
          state: 1,
        },
      } as GetCurrentUserResponse;
    }

    throw new Error("Invalid /auth/me response");
  },
};

