function decodePayload(token) {
  try {
    const part = token.split(".")[1];
    if (!part) return null;
    const json = atob(part.replace(/-/g, "+").replace(/_/g, "/"));
    return JSON.parse(json);
  } catch {
    return null;
  }
}

export function roleFromJwt(token) {
  const p = decodePayload(token);
  if (!p) return "";

  if (Array.isArray(p.roleIds) && p.roleIds.length > 0) {
    const ids = p.roleIds.map((id) => Number(id));
    if (ids.includes(1)) return "admin";
    if (ids.includes(4)) return "executer/varifier";
    if (ids.includes(2)) return "user";
    if (ids.includes(3)) return "support";
  }

  const roleValue =
    (Array.isArray(p.roles) && p.roles[0]) || p.role || p.role_name || "";
  return String(roleValue).trim().toLowerCase().replace(/\s*\/\s*/g, "/");
}

export function userFromJwt(token) {
  const p = decodePayload(token);
  if (!p) return null;
  return {
    userId: p.userId ?? p.user_id ?? p.id,
    employeeName: p.employeeName ?? p.name ?? p.employee_name ?? "HSE User",
    email: p.email ?? p.email_id ?? "",
  };
}

export function rolesFromJwt(token) {
  const p = decodePayload(token);
  if (!p) return [];
  if (Array.isArray(p.roles)) return p.roles;
  if (p.role) return [p.role];
  return [];
}

export function roleIdsFromJwt(token) {
  const p = decodePayload(token);
  if (!p) return [];
  if (Array.isArray(p.roleIds)) return p.roleIds.map(Number);
  if (p.role_id != null) return [Number(p.role_id)];
  return [];
}

export function isAdminRole(role) {
  return String(role || "")
    .trim()
    .toLowerCase() === "admin";
}
