import * as fs from 'node:fs';
import * as os from 'node:os';
import * as path from 'node:path';
import { loadExternalConfig } from '../../src/comm/config-loader';

describe('loadExternalConfig', () => {
  it('在 pkg 模式读取 exe 同目录下的 config.yaml', () => {
    const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'neta-config-'));
    fs.mkdirSync(path.join(tempDir, 'data'), { recursive: true });
    fs.writeFileSync(
      path.join(tempDir, 'config.yaml'),
      [
        'server:',
        '  port: 8100',
        'data:',
        `  dir: "${path.join(tempDir, 'data').replace(/\\/g, '\\\\')}"`,
        'autoOpenBrowser: true',
        'database:',
        '  type: mysql',
        '  host: db.example.com',
        '  port: 3306',
        '  username: demo',
        '  password: secret',
        '  database: neta_test',
      ].join('\n'),
      'utf8'
    );

    const loaded = loadExternalConfig({ isPkg: true, execPath: path.join(tempDir, 'backend.exe') });
    expect(loaded.server.port).toBe(8100);
    expect(loaded.database.host).toBe('db.example.com');
    expect(loaded.data.dir).toContain(path.join('data'));
  });

  it('在开发模式允许没有 config.yaml 并回退到内置默认值', () => {
    const loaded = loadExternalConfig({ isPkg: false, cwd: '/tmp/neta-backend' });
    expect(loaded.source).toBe('fallback');
  });
});
