import { afterEach, describe, expect, test } from 'bun:test';

import { getBetterAuthBaseUrl, getDeviceOnlineStaleSeconds, getFirstDefinedEnv } from '../utils/env';

const ORIGINAL_ENV = { ...process.env };

afterEach(() => {
  process.env = { ...ORIGINAL_ENV };
});

describe('env helpers', () => {
  test('getFirstDefinedEnv returns first set value', () => {
    process.env.TEST_A = '';
    process.env.TEST_B = ' value-b ';

    expect(getFirstDefinedEnv('TEST_A', 'TEST_B')).toBe('value-b');
  });

  test('getBetterAuthBaseUrl prefers BETTER_AUTH_BASE_URL over legacy var', () => {
    process.env.BETTER_AUTH_BASE_URL = 'http://base-url:4000';
    process.env.BETTER_AUTH_URL = 'http://legacy:3000';

    expect(getBetterAuthBaseUrl()).toBe('http://base-url:4000');
  });

  test('getDeviceOnlineStaleSeconds defaults to 30', () => {
    delete process.env.DEVICE_ONLINE_STALE_SECONDS;
    expect(getDeviceOnlineStaleSeconds()).toBe(30);
  });

  test('getDeviceOnlineStaleSeconds parses valid positive integer values', () => {
    process.env.DEVICE_ONLINE_STALE_SECONDS = '45';
    expect(getDeviceOnlineStaleSeconds()).toBe(45);
  });

  test('getDeviceOnlineStaleSeconds falls back to default on invalid values', () => {
    process.env.DEVICE_ONLINE_STALE_SECONDS = '0';
    expect(getDeviceOnlineStaleSeconds()).toBe(30);

    process.env.DEVICE_ONLINE_STALE_SECONDS = '-2';
    expect(getDeviceOnlineStaleSeconds()).toBe(30);

    process.env.DEVICE_ONLINE_STALE_SECONDS = 'abc';
    expect(getDeviceOnlineStaleSeconds()).toBe(30);
  });
});
