/**
 * Role IDs: 1=Admin, 3=User, 4=Support (Auditor role_id 2 has been removed).
 * Support role (role_id 4) has access only to Tickets section.
 */
import { getToken } from 'hse-auth';

export const ROLE_SUPPORT_ID = 4;

/**
 * Decode JWT payload segment (handles base64url as produced by jsonwebtoken and most issuers).
 * @param {string} [token] - JWT token; if omitted, reads from hse-auth storage
 * @returns {object|null} decoded payload or null if missing/invalid
 */
function decodeTokenPayload(token) {
  const t = token || (typeof localStorage !== 'undefined' ? getToken() : null);
  if (!t) return null;
  try {
    const payload = t.split('.')[1];
    if (!payload) return null;
    const base64 = payload.replace(/-/g, '+').replace(/_/g, '/');
    const padded = base64 + '='.repeat((4 - (base64.length % 4)) % 4);
    return JSON.parse(atob(padded));
  } catch (e) {
    return null;
  }
}

/**
 * Get current user id from JWT token.
 * @param {string} [token] - JWT token; if omitted, uses localStorage
 * @returns {number|null} userId or null if missing/invalid
 */
export function getUserIdFromToken(token) {
  const decoded = decodeTokenPayload(token);
  if (!decoded) return null;
  const id = decoded.userId ?? decoded.user_id ?? decoded.id;
  if (id == null) return null;
  return Number(id);
}

/**
 * Get roleIds array from JWT token (optional token; otherwise reads from localStorage).
 * @param {string} [token] - JWT token; if omitted, reads from hse-auth storage
 * @returns {number[]} roleIds array, or [] if missing/invalid
 */
export function getRoleIdsFromToken(token) {
  const decoded = decodeTokenPayload(token);
  if (!decoded) return [];
  const ids = decoded.roleIds ?? decoded.role_ids;
  if (!Array.isArray(ids)) return [];
  return ids.map((id) => Number(id)).filter((n) => !Number.isNaN(n));
}

/**
 * Get display name from JWT (employeeName or email).
 * @param {string} [token] - JWT token; if omitted, uses localStorage
 * @returns {string} display name or empty string
 */
export function getDisplayNameFromToken(token) {
  const decoded = decodeTokenPayload(token);
  if (!decoded) return '';
  return decoded.employeeName || decoded.email || '';
}

/**
 * True when the user has only the Support role (role_id 4).
 * Such users can access only ticket-related routes and see only Tickets in the navbar.
 * @param {string} [token] - Optional JWT; if omitted, uses localStorage
 * @returns {boolean}
 */
export function isSupportOnlyUser(token) {
  const roleIds = getRoleIdsFromToken(token);
  return roleIds.length === 1 && roleIds[0] === ROLE_SUPPORT_ID;
}

/** Ticket routes that Support role is allowed to access */
export const TICKET_ROUTES = ['/tickets', '/raise-ticket', '/close-ticket', '/ticket-logs'];

export function isTicketRoute(pathname) {
  return TICKET_ROUTES.some((route) => pathname === route || pathname.startsWith(route + '/'));
}
