import { getDeviceOnlineStaleSeconds } from './env';

export type EffectiveDeviceStatus = 'online' | 'offline';

type EffectiveDeviceStatusParams = {
  status: string | null | undefined;
  lastSeenAt: Date | null | undefined;
  now?: Date;
  staleAfterSeconds?: number;
};

export const getEffectiveDeviceStatus = ({
  status,
  lastSeenAt,
  now = new Date(),
  staleAfterSeconds = getDeviceOnlineStaleSeconds(),
}: EffectiveDeviceStatusParams): EffectiveDeviceStatus => {
  if (status !== 'online') {
    return 'offline';
  }

  if (!(lastSeenAt instanceof Date) || Number.isNaN(lastSeenAt.getTime())) {
    return 'offline';
  }

  const elapsedMs = now.getTime() - lastSeenAt.getTime();
  if (elapsedMs < 0) {
    return 'online';
  }

  return elapsedMs <= staleAfterSeconds * 1000 ? 'online' : 'offline';
};
