const getEnvValue = (name: string): string | undefined => {
  const value = process.env[name];
  if (!value) {
    return undefined;
  }

  const trimmed = value.trim();
  return trimmed.length > 0 ? trimmed : undefined;
};

export const getFirstDefinedEnv = (...names: string[]): string | undefined => {
  for (const name of names) {
    const value = getEnvValue(name);
    if (value) {
      return value;
    }
  }

  return undefined;
};

export const getRequiredEnv = (name: string): string => {
  const value = getEnvValue(name);

  if (!value) {
    throw new Error(`${name} is required. Add it to your .env file.`);
  }

  return value;
};

export const getBetterAuthBaseUrl = (): string => {
  return getFirstDefinedEnv('BETTER_AUTH_BASE_URL', 'BETTER_AUTH_URL') ?? `http://localhost:${process.env.PORT ?? '3000'}`;
};

const DEFAULT_DEVICE_ONLINE_STALE_SECONDS = 30;

export const getDeviceOnlineStaleSeconds = (): number => {
  const value = getFirstDefinedEnv('DEVICE_ONLINE_STALE_SECONDS');
  if (!value) {
    return DEFAULT_DEVICE_ONLINE_STALE_SECONDS;
  }

  const parsed = Number(value);
  if (!Number.isInteger(parsed) || parsed <= 0) {
    return DEFAULT_DEVICE_ONLINE_STALE_SECONDS;
  }

  return parsed;
};
