import assert from "node:assert/strict";
import { describe, it } from "vitest";
import { getEnvApiKey } from "./env-api-keys.js";

describe("getEnvApiKey", () => {
	it("uses GEMINI_API_KEY for google when present", () => {
		const savedGemini = process.env.GEMINI_API_KEY;
		const savedGoogleGenerative = process.env.GOOGLE_GENERATIVE_AI_API_KEY;

		process.env.GEMINI_API_KEY = "gemini-key";
		process.env.GOOGLE_GENERATIVE_AI_API_KEY = "google-generative-key";

		try {
			assert.equal(getEnvApiKey("google"), "gemini-key");
		} finally {
			if (savedGemini === undefined) delete process.env.GEMINI_API_KEY;
			else process.env.GEMINI_API_KEY = savedGemini;
			if (savedGoogleGenerative === undefined)
				delete process.env.GOOGLE_GENERATIVE_AI_API_KEY;
			else process.env.GOOGLE_GENERATIVE_AI_API_KEY = savedGoogleGenerative;
		}
	});

	it("accepts GOOGLE_GENERATIVE_AI_API_KEY for google", () => {
		const savedGemini = process.env.GEMINI_API_KEY;
		const savedGoogleGenerative = process.env.GOOGLE_GENERATIVE_AI_API_KEY;

		delete process.env.GEMINI_API_KEY;
		process.env.GOOGLE_GENERATIVE_AI_API_KEY = "google-generative-key";

		try {
			assert.equal(getEnvApiKey("google"), "google-generative-key");
		} finally {
			if (savedGemini === undefined) delete process.env.GEMINI_API_KEY;
			else process.env.GEMINI_API_KEY = savedGemini;
			if (savedGoogleGenerative === undefined)
				delete process.env.GOOGLE_GENERATIVE_AI_API_KEY;
			else process.env.GOOGLE_GENERATIVE_AI_API_KEY = savedGoogleGenerative;
		}
	});

	it("uses the OpenCode Go subscription key before the Zen key", () => {
		const savedZen = process.env.OPENCODE_API_KEY;
		const savedGo = process.env.OPENCODE_GO_API_KEY;

		process.env.OPENCODE_API_KEY = "zen-key";
		process.env.OPENCODE_GO_API_KEY = "go-key";

		try {
			assert.equal(getEnvApiKey("opencode"), "zen-key");
			assert.equal(getEnvApiKey("opencode-go"), "go-key");
		} finally {
			if (savedZen === undefined) delete process.env.OPENCODE_API_KEY;
			else process.env.OPENCODE_API_KEY = savedZen;
			if (savedGo === undefined) delete process.env.OPENCODE_GO_API_KEY;
			else process.env.OPENCODE_GO_API_KEY = savedGo;
		}
	});
});
