// @vitest-environment node

import type { ConfigEnv, UserConfig, UserConfigFn } from 'vite';

import { createServer } from 'vite';
import { afterAll, beforeAll, describe, expect, it } from 'vitest';

import config from '../vite.config';

const DEVELOPMENT_BASE_PATH = '/onlyoffice-plugins/0.1.0-dev/dms-qianpiye-annotator/';

function resolveConfig(command: ConfigEnv['command']): UserConfig {
  expect(config).toBeTypeOf('function');
  const resolved = (config as UserConfigFn)({
    command,
    isPreview: false,
    isSsrBuild: false,
    mode: command === 'serve' ? 'development' : 'production',
  });
  if (resolved instanceof Promise) throw new Error('测试要求 Vite 配置同步解析');
  return resolved;
}

describe('签批页标注 Vite 配置', () => {
  let server: Awaited<ReturnType<typeof createServer>>;

  beforeAll(async () => {
    const development = resolveConfig('serve');
    server = await createServer({
      ...development,
      configFile: false,
      server: { ...development.server, host: '127.0.0.1', port: 0, strictPort: false },
    });
    await server.listen();
  });

  afterAll(async () => {
    await server?.close();
  });

  it('开发服务在后端下发的 release 路径返回 manifest JSON', async () => {
    const address = server.httpServer?.address();
    if (!address || typeof address === 'string') throw new Error('Vite 测试服务没有可用监听端口');

    const response = await fetch(`http://127.0.0.1:${address.port}${DEVELOPMENT_BASE_PATH}config.json`);

    expect(response.status).toBe(200);
    expect(response.headers.get('content-type')).toContain('application/json');
    await expect(response.json()).resolves.toMatchObject({
      name: '签批页标注',
      guid: 'asc.{C764F7D6-055D-4C7D-97FD-83D2C4440585}',
      version: '0.1.0',
      variations: [{ icons: ['resources/icon.png', 'resources/icon@2x.png'] }],
    });
  });

  it('开发服务加载 OnlyOffice SDK，生产包保留相对 SDK 路径', async () => {
    const address = server.httpServer?.address();
    if (!address || typeof address === 'string') throw new Error('Vite 测试服务没有可用监听端口');

    const developmentHtml = await (await fetch(`http://127.0.0.1:${address.port}${DEVELOPMENT_BASE_PATH}index.html`)).text();
    expect(developmentHtml).toContain('href="/onlyoffice-sdk/v1/plugins.css"');
    expect(developmentHtml).toContain('src="/onlyoffice-sdk/v1/plugins.js"');

    const productionHtml = await import('node:fs/promises').then(({ readFile }) => readFile(new URL('../index.html', import.meta.url), 'utf8'));
    expect(productionHtml).toContain('href="../v1/plugins.css"');
    expect(productionHtml).toContain('src="../v1/plugins.js"');
  });

  it('生产构建继续使用相对资源路径', () => {
    expect(resolveConfig('build').base).toBe('./');
  });
});
