import { afterEach, describe, expect, it, vi } from "vitest";
import { getRuntimeSecretStatuses, resolveSystemSettingsRuntime } from "../lib/system-settings-runtime.js";

describe("system settings runtime resolution", () => {
  afterEach(() => {
    vi.unstubAllEnvs();
  });

  it("prefers OPENAI_API_KEY for direct OpenAI runtime settings", () => {
    vi.stubEnv("OPENAI_API_KEY", "env-openai-key");
    vi.stubEnv("AZURE_OPENAI_API_KEY", "env-azure-key");

    const settings = resolveSystemSettingsRuntime({
      aiProvider: "openai",
      azureOpenAiApiKey: "db-key",
    });

    expect(settings.azureOpenAiApiKey).toBe("env-openai-key");
  });

  it("prefers AZURE_OPENAI_API_KEY for Azure runtime settings", () => {
    vi.stubEnv("OPENAI_API_KEY", "env-openai-key");
    vi.stubEnv("AZURE_OPENAI_API_KEY", "env-azure-key");

    const settings = resolveSystemSettingsRuntime({
      aiProvider: "azure",
      azureOpenAiApiKey: "db-key",
    });

    expect(settings.azureOpenAiApiKey).toBe("env-azure-key");
  });

  it("ignores blank environment overrides", () => {
    vi.stubEnv("SMTP_PASSWORD", "   ");

    const settings = resolveSystemSettingsRuntime({
      smtpPassword: "db-password",
    });

    expect(settings.smtpPassword).toBe("db-password");
  });

  it("reports active source and legacy DB presence separately", () => {
    vi.stubEnv("OPENAI_API_KEY", "env-openai-key");

    const statuses = getRuntimeSecretStatuses({
      aiProvider: "openai",
      azureOpenAiApiKey: "db-key",
      smtpPassword: "db-password",
    });

    expect(statuses.azureOpenAiApiKey).toEqual({
      configured: true,
      activeSource: "environment",
      hasStoredValue: true,
      envVarNames: ["OPENAI_API_KEY", "AZURE_OPENAI_API_KEY"],
    });
    expect(statuses.smtpPassword).toEqual({
      configured: true,
      activeSource: "database",
      hasStoredValue: true,
      envVarNames: ["SMTP_PASSWORD"],
    });
  });
});
