function authHeaders(): Record<string, string> {
  // If you store token in cookies on server, read it here instead.
  // For now, this keeps build happy and won't add Authorization when no token exists.
  const token =
      typeof window !== "undefined"
          ? localStorage.getItem("auth_token")
          : null;

  return token ? { Authorization: `Bearer ${token}` } : {};
}
// src/api/profile.ts
import { BASE_URL, forceLogout, parseJsonOrLogout } from "@/constants";

type SaveUserSettingPayload = {
  key: string;
  value: string;
  user_id: string;
  token: string;
};

type UserSettings = {
  brand: string;
  theme: string;
  effect: string;
  sound: string;
  speed: string;
  mode: string;
};

type UserLevel = {
  lavel: number;
  next: number;
  xp: number;
};

export type AppUser = {
  userId: string;
  image: Record<string, unknown>;
  name: string;
  balance: number;
  level: UserLevel;
  settings: UserSettings;
  token: string;
};

type SaveUserSettingResponse = {
  resp: "success" | "error";
  msg: string;
  user?: {
    user: AppUser;
  };
};

export const saveUserSetting = async (payload: SaveUserSettingPayload) => {
  const res = await fetch(`${BASE_URL}/api/save-user-settings`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${payload.token}`,
    },
    body: JSON.stringify(payload),
  });
  return parseJsonOrLogout(res);
};

export const updateSession = async (user: AppUser) => {
  const headers: Record<string, string> = {
    "Content-Type": "application/json",
    ...authHeaders(),
  };

  const res = await fetch(`${BASE_URL}/api/session`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${user.token}`,
    },
    body: JSON.stringify({ user }), // exactly like your example
  });

  const data = await res.json();

  if (!res.ok) {
    forceLogout();
    throw new Error("Failed to update session");
  }

  return data as Promise<{ success: boolean }>;
};
