import Cookies from 'js-cookie';

export const SESSION_HEADER_KEYS = {
  tenantId: 'x-tenant-id',
  organizationUnitId: 'x-organization-unit-id',
  currentPositionId: 'x-current-position-id',
  currentProjectId: 'x-current-project-id',
} as const;

const TOKEN_STORAGE_KEYS = [
  'ema-backoffice-auth-token',
  'ema-portal-auth-token',
  'auth-token',
] as const;

export function resolveTokenFromStorage(): string | undefined {
  // cookie first, then localStorage (legacy pre-migration sessions)
  for (const key of TOKEN_STORAGE_KEYS) {
    const cookie = Cookies.get(key);
    if (cookie) return cookie;
    const stored = localStorage.getItem(key);
    if (stored) return stored;
  }
  return undefined;
}

export function resolveSessionContext(state?: { auth?: { token?: string } }): {
  token: string | undefined;
  sessionHeaders: Record<string, string>;
} {
  const token = state?.auth?.token ?? resolveTokenFromStorage();
  return { token, sessionHeaders: {} };
}
