import { BASE_URL, forceLogout, parseJsonOrLogout } from "@/constants";

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

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

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

export const saveUserSetting = async (
  payload: SaveUserSettingPayload,
): Promise<SaveUserSettingResponse> => {
  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 getUserSettings = async (args: {
  user_id: string;
  token: string;
}): Promise<UserSettings> => {
  const res = await fetch(
    `${BASE_URL}/api/user-settings?user_id=${encodeURIComponent(args.user_id)}`,
    {
      method: "POST",
      headers: {
        Authorization: `Bearer ${args.token}`,
      },
      cache: "no-store", // ensure fresh
    },
  );

  return parseJsonOrLogout(res);
};

// balance
export const fetchBalanceHistory = async (
  user_id: string,
  token: string,
  next = 0,
) => {
  const res = await fetch(`${BASE_URL}/api/balance-history`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    },
    body: JSON.stringify({ user_id, next }),
  });

  return parseJsonOrLogout(res);
};

// shipping
export const fetchShippingHistory = async (
  user_id: string,
  token: string,
  next = 0,
) => {
  const res = await fetch(`${BASE_URL}/api/shipping`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    },
    body: JSON.stringify({ user_id, next }),
  });

  return parseJsonOrLogout(res);
};

// pack
export const fetchPacksHistory = async (
  user_id: string,
  token: string,
  next = 0,
) => {
  const res = await fetch(`${BASE_URL}/api/packs-anl`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    },
    body: JSON.stringify({ user_id, next }),
  });

  return parseJsonOrLogout(res);
};

// Affiliate

export const fetchAffiliateAnalytics = async (
  user_id: string,
  token: string,
) => {
  const res = await fetch(`${BASE_URL}/api/affiliate-anl`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    },
    body: JSON.stringify({ user_id }),
  });

  return parseJsonOrLogout(res);
};

export const fetchWithdrawBalance = async (user_id: string, token: string) => {
  const res = await fetch(`${BASE_URL}/api/withdraw-balance`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    },
    body: JSON.stringify({ user_id }),
  });

  return parseJsonOrLogout(res);
};

// api/profile.ts
export async function getShippingCards(
  userId: string,
  token: string,
  order: number,
) {
  const res = await fetch(`${BASE_URL}/api/get-shipping-cards`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    },
    body: JSON.stringify({ user_id: userId, order }),
  });

  return parseJsonOrLogout(res);
}

export async function uploadUserImage(
  userId: string,
  file: File,
  token?: string,
) {
  const form = new FormData();
  form.append("image", file);
  form.append("user_id", userId);

  const res = await fetch(`${BASE_URL}/api/upload-user-image`, {
    method: "POST",
    body: form,
    headers: token ? { Authorization: `Bearer ${token}` } : undefined, // only if your backend needs it
  });
  // If backend returns non-2xx but still JSON, handle it:
  const data = await parseJsonOrLogout(res);

  // expected: { resp:"success", message:"...", path:"https://..." }
  return data;
}

export async function setUserName(
  userId: string,
  name: string,
  token?: string,
) {
  const res = await fetch(`${BASE_URL}/api/set-name`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      ...(token ? { Authorization: `Bearer ${token}` } : {}),
    },
    body: JSON.stringify({
      user_id: userId,
      name,
    }),
  });

  const data = await parseJsonOrLogout(res);

  return data;
}

export const getHomePage = async (user_id: string, token: string) => {
  const res = await fetch(`${BASE_URL}/api/homepage`, {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
      Authorization: `Bearer ${token}`,
    },
    body: JSON.stringify({
      user_id,
    }),
  });

  return parseJsonOrLogout(res);
};

export const getRefCode = async (userId: string, token: string) => {
  const res = await fetch(`${BASE_URL}/api/set-ref?user_id=${userId}`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${token}`,
      Accept: "application/json",
    },
    cache: "no-store",
  });

  return parseJsonOrLogout(res);
};

export const getPackCards = async (
  userId: string,
  token: string,
  pack_id: any,
) => {
  const res = await fetch(
    `${BASE_URL}/api/get-opened-cards?user_id=${userId}&pack_id=${pack_id}`,
    {
      method: "POST",
      headers: {
        Authorization: `Bearer ${token}`,
        Accept: "application/json",
        "Content-Type": "application/json",
      },
    },
  );
  return parseJsonOrLogout(res);
};
