/**
 * Tests for ApiKeyManager.getEmbeddingApiKey — the per-provider key
 * accessor wired into EmbeddingService.
 *
 * Pins the wiring contract:
 *   - azure   → loxiaApiKey (Loxia-backend proxy auth)
 *   - openai  → vendorKeys.openai (BYOK direct-to-OpenAI)
 *   - local   → null (no key needed)
 *   - disabled→ null
 *   - unknown → null (defensive; no throw)
 */

import { describe, test, expect, beforeEach, jest } from '@jest/globals';

// Avoid touching disk; mock persistence helpers so apiKeyManager can be
// instantiated in pure-memory mode.
jest.unstable_mockModule('../../utilities/userDataDir.js', () => ({
  ensureUserDataDirs: jest.fn(async () => ({ settings: '/tmp/fake' })),
  getUserDataPaths: jest.fn(() => ({ settings: '/tmp/fake' })),
}));

const { default: ApiKeyManager } = await import('../apiKeyManager.js');

describe('ApiKeyManager.getEmbeddingApiKey', () => {
  let mgr;
  beforeEach(() => {
    mgr = new ApiKeyManager(null);
    mgr.keys = {
      loxiaApiKey: 'loxia-abc',
      vendorKeys: { openai: 'sk-openai-xyz' },
    };
  });

  test('azure → loxiaApiKey', () => {
    expect(mgr.getEmbeddingApiKey('azure')).toBe('loxia-abc');
  });

  test('openai → vendorKeys.openai', () => {
    expect(mgr.getEmbeddingApiKey('openai')).toBe('sk-openai-xyz');
  });

  test('azure-custom → vendorKeys.azureCustom', () => {
    mgr.keys.vendorKeys.azureCustom = 'sk-azure-custom-123';
    expect(mgr.getEmbeddingApiKey('azure-custom')).toBe('sk-azure-custom-123');
  });

  test('azure-custom with no key configured → null', () => {
    expect(mgr.getEmbeddingApiKey('azure-custom')).toBeNull();
  });

  test('local → null (no key needed)', () => {
    expect(mgr.getEmbeddingApiKey('local')).toBeNull();
  });

  test('disabled → null', () => {
    expect(mgr.getEmbeddingApiKey('disabled')).toBeNull();
  });

  test('unknown provider → null (defensive, no throw)', () => {
    expect(mgr.getEmbeddingApiKey('cohere')).toBeNull();
    expect(mgr.getEmbeddingApiKey(null)).toBeNull();
    expect(mgr.getEmbeddingApiKey(undefined)).toBeNull();
  });

  test('missing loxiaApiKey → azure returns null (not undefined)', () => {
    mgr.keys.loxiaApiKey = null;
    expect(mgr.getEmbeddingApiKey('azure')).toBeNull();
  });

  test('missing openai vendor key → openai returns null', () => {
    mgr.keys.vendorKeys = {};
    expect(mgr.getEmbeddingApiKey('openai')).toBeNull();
  });

  test('missing vendorKeys map entirely → openai returns null', () => {
    mgr.keys.vendorKeys = undefined;
    expect(mgr.getEmbeddingApiKey('openai')).toBeNull();
  });

  test('keys object entirely missing → all providers return null', () => {
    mgr.keys = null;
    for (const p of ['azure', 'openai', 'local', 'disabled']) {
      expect(mgr.getEmbeddingApiKey(p)).toBeNull();
    }
  });
});
