import { afterEach, describe, expect, it, vi } from 'vitest';
import { gatewayOrigin } from './origin';

describe('gatewayOrigin', () => {
  afterEach(() => {
    vi.unstubAllEnvs();
    vi.unstubAllGlobals();
  });

  it('returns the configured VITE_GATEWAY_URL (the packaged native build)', () => {
    vi.stubEnv('VITE_GATEWAY_URL', 'https://erudit-game.ru');
    // Even with a page origin present, the configured gateway wins (native loads from a local origin).
    vi.stubGlobal('location', { origin: 'https://localhost' });
    expect(gatewayOrigin()).toBe('https://erudit-game.ru');
  });

  it('falls back to the page origin when VITE_GATEWAY_URL is unset (web/mock)', () => {
    vi.stubEnv('VITE_GATEWAY_URL', '');
    vi.stubGlobal('location', { origin: 'https://erudit-game.ru' });
    expect(gatewayOrigin()).toBe('https://erudit-game.ru');
  });

  it('returns an empty string with neither a configured gateway nor a location (server-side)', () => {
    vi.stubEnv('VITE_GATEWAY_URL', '');
    // No location stub — location is undefined in the node test env, so the path degrades to relative.
    expect(gatewayOrigin()).toBe('');
  });
});
