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

const HSE_ADMIN_ROLE_ID = 1;

function normalizeRoleName(value) {
  return value ? String(value).trim().toLowerCase() : "";
}

/** SAT HSE tokens use `roles[]` + `roleIds[]`, not always a single `role` field. */
export function roleFromJwt(token) {
  const json = decodeJwtPayload(token);
  if (!json) return null;

  const roleIds = Array.isArray(json.roleIds)
    ? json.roleIds.map((id) => Number(id)).filter((n) => !Number.isNaN(n))
    : [];
  if (roleIds.includes(HSE_ADMIN_ROLE_ID)) {
    return "admin";
  }

  const roleNames = Array.isArray(json.roles) ? json.roles : [];
  if (
    roleNames.some((name) => normalizeRoleName(name) === "admin") ||
    json.isAdmin === true
  ) {
    return "admin";
  }

  const roleValue =
    json.role ??
    json.role_name ??
    (roleNames.length > 0 ? roleNames[0] : null);
  return roleValue ? normalizeRoleName(roleValue) : null;
}

export function userFromJwt(token) {
  const json = decodeJwtPayload(token);
  if (!json) return null;
  const role =
    json.role ??
    (Array.isArray(json.roles) ? json.roles[0] : null) ??
    json.role_name;
  return {
    user_id: json.user_id ?? json.userId ?? json.sub,
    employee_name: json.employee_name ?? json.name ?? "HSE User",
    email_id: json.email ?? json.email_id,
    role_name: role,
  };
}
