import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
import { mkdtempSync, statSync } from 'fs';
import { tmpdir } from 'os';
import { join } from 'path';

describe('auth/gemini', () => {
  const originalHome = process.env.HOME;
  const originalGeminiEnvKey = process.env.GEMINI_API_KEY;
  const originalGoogleEnvKey = process.env.GOOGLE_API_KEY;

  let homeDir: string;

  beforeEach(() => {
    homeDir = mkdtempSync(join(tmpdir(), 'flynn-auth-gemini-'));
    process.env.HOME = homeDir;
    delete process.env.GEMINI_API_KEY;
    delete process.env.GOOGLE_API_KEY;
    vi.resetModules();
  });

  afterEach(() => {
    process.env.HOME = originalHome;
    if (originalGeminiEnvKey) {
      process.env.GEMINI_API_KEY = originalGeminiEnvKey;
    } else {
      delete process.env.GEMINI_API_KEY;
    }

    if (originalGoogleEnvKey) {
      process.env.GOOGLE_API_KEY = originalGoogleEnvKey;
    } else {
      delete process.env.GOOGLE_API_KEY;
    }
  });

  it('stores, loads, and clears Gemini API key', async () => {
    const mod = await import('./gemini.js');

    expect(mod.loadStoredGeminiAuth()).toBeNull();

    mod.storeGeminiAuth('gem-test');
    expect(mod.loadStoredGeminiAuth()?.api_key).toBe('gem-test');

    const authFile = join(homeDir, '.config/flynn/auth.json');
    const mode = statSync(authFile).mode & 0o777;
    expect(mode).toBe(0o600);

    mod.clearGeminiAuth();
    expect(mod.loadStoredGeminiAuth()).toBeNull();
  });

  it('getGeminiApiKey prefers GEMINI_API_KEY over GOOGLE_API_KEY', async () => {
    process.env.GEMINI_API_KEY = 'gem-env';
    process.env.GOOGLE_API_KEY = 'google-env';
    const mod = await import('./gemini.js');
    expect(mod.getGeminiApiKey()).toBe('gem-env');
  });

  it('getGeminiApiKey falls back to GOOGLE_API_KEY', async () => {
    process.env.GOOGLE_API_KEY = 'google-env';
    const mod = await import('./gemini.js');
    expect(mod.getGeminiApiKey()).toBe('google-env');
  });
});
