/* @vitest-environment happy-dom */

import { afterEach, describe, expect, it, vi } from 'vitest';

import { getDocumentServerUrl } from '../loadDocsApi';

const RUNTIME_KEY = '_JNPF_ADMIN_PRO_APP_CONF_';

function setRuntimeConfig(value: Record<string, string> | undefined) {
  if (value === undefined) delete (window as any)[RUNTIME_KEY];
  else (window as any)[RUNTIME_KEY] = value;
}

describe('getDocumentServerUrl', () => {
  afterEach(() => {
    setRuntimeConfig(undefined);
    vi.unstubAllEnvs();
  });

  it('优先使用运行时 _app.config.js 注入的地址（由部署环境 .env 决定）', () => {
    vi.stubEnv('VITE_GLOB_ONLYOFFICE_URL', 'http://build-time:20000');
    setRuntimeConfig({ VITE_GLOB_ONLYOFFICE_URL: 'http://document-server.example:20000' });
    expect(getDocumentServerUrl()).toBe('http://document-server.example:20000');
  });

  it('运行时为空时回落到构建期变量（本地开发 .env.development）', () => {
    vi.stubEnv('VITE_GLOB_ONLYOFFICE_URL', 'http://localhost:20000');
    setRuntimeConfig({ VITE_GLOB_ONLYOFFICE_URL: '' });
    expect(getDocumentServerUrl()).toBe('http://localhost:20000');
  });

  it('没有运行时配置对象时回落到构建期变量', () => {
    vi.stubEnv('VITE_GLOB_ONLYOFFICE_URL', 'http://localhost:20000');
    expect(getDocumentServerUrl()).toBe('http://localhost:20000');
  });

  it('两处都没配置时返回空串，调用方据此提示未配置', () => {
    vi.stubEnv('VITE_GLOB_ONLYOFFICE_URL', '');
    expect(getDocumentServerUrl()).toBe('');
  });

  it('去掉末尾斜杠', () => {
    setRuntimeConfig({ VITE_GLOB_ONLYOFFICE_URL: 'http://document-server.example:20000/' });
    expect(getDocumentServerUrl()).toBe('http://document-server.example:20000');
  });
});
