import type { ClientMembership, LauncherUser } from "../../entities/user/types";
import type { LauncherData } from "./mockApi";

export interface ProfileResponse {
  user: LauncherUser;
  memberships: ClientMembership[];
}

export interface ProfileMutationResult {
  data: LauncherData;
}

export async function fetchOwnProfile(): Promise<ProfileResponse> {
  return requestJson<ProfileResponse>("/api/profile");
}

export async function updateOwnProfile(patch: Partial<LauncherUser>): Promise<ProfileMutationResult> {
  return requestJson<ProfileMutationResult>("/api/profile", {
    method: "PATCH",
    body: JSON.stringify(patch),
  });
}

export async function updateOwnPassword(newPassword: string): Promise<ProfileMutationResult> {
  return requestJson<ProfileMutationResult>("/api/profile/password", {
    method: "POST",
    body: JSON.stringify({ newPassword }),
  });
}

async function requestJson<T>(url: string, init: RequestInit = {}): Promise<T> {
  const headers = new Headers(init.headers);

  if (!headers.has("Content-Type")) {
    headers.set("Content-Type", "application/json");
  }

  const response = await fetch(url, {
    ...init,
    headers,
  });

  if (!response.ok) {
    throw new Error(await readErrorMessage(response));
  }

  return (await response.json()) as T;
}

async function readErrorMessage(response: Response) {
  try {
    const payload = (await response.json()) as { error?: string };
    return payload.error ?? response.statusText;
  } catch {
    return response.statusText;
  }
}
