import { describe, it, expect, afterEach } from 'vitest';
import { loadConfig } from './config.js';
import { writeFileSync, unlinkSync, mkdtempSync, rmSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';

describe('AuthConfig loading', () => {
  const tmpConfig = join(process.cwd(), '_test_config_auth.yaml');

  afterEach(() => {
    try { unlinkSync(tmpConfig); } catch { /* ignore */ }
  });

  it('returns undefined auth when auth section is absent', () => {
    writeFileSync(tmpConfig, 'language: ja\nprovider:\n  model: test\n  base_url: http://localhost\n');
    const config = loadConfig(tmpConfig);
    expect(config.auth).toBeUndefined();
  });

  it('parses auth section with snake_case keys', () => {
    writeFileSync(tmpConfig, `
language: ja
provider:
  model: test
  base_url: http://localhost
auth:
  session_secret: "test-secret"
  session_max_age: 3600000
  admin_emails:
    - admin@test.com
  providers:
    google:
      client_id: "gid"
      client_secret: "gsecret"
      callback_url: "http://localhost/auth/google/callback"
`);
    const config = loadConfig(tmpConfig);
    expect(config.auth).toBeDefined();
    expect(config.auth!.sessionSecret).toBe('test-secret');
    expect(config.auth!.sessionMaxAge).toBe(3600000);
    expect(config.auth!.adminEmails).toEqual(['admin@test.com']);
    expect(config.auth!.providers.google.clientId).toBe('gid');
  });

  it('parses auth.primary_provider from YAML', () => {
    const tmp = mkdtempSync(join(tmpdir(), 'config-primary-'));
    const path = join(tmp, 'config.yaml');
    writeFileSync(path, `
auth:
  session_secret: s
  admin_emails: [a@x.com]
  primary_provider: gitea
  providers:
    gitea:
      client_id: cid
      client_secret: cs
      callback_url: http://cb
      base_url: http://gitea.local
`.trim());
    try {
      const cfg = loadConfig(path);
      expect(cfg.auth?.primaryProvider).toBe('gitea');
    } finally {
      rmSync(tmp, { recursive: true, force: true });
    }
  });
});
