import { describe, expect, test } from "bun:test"
import {
  hasSaeeolIndexingAuth,
  resolveSaeeolIndexingAuth,
  shouldDefaultIndexingToSaeeol,
} from "../../src/overlay/indexing-auth"

describe("Saeeol indexing auth resolution", () => {
  test("detects auth from explicit indexing Saeeol config", () => {
    const auth = resolveSaeeolIndexingAuth({
      config: { indexing: { saeeol: { apiKey: "idx-token", baseUrl: "https://idx.test", organizationId: "org_idx" } } },
    })

    expect(auth).toEqual({ apiKey: "idx-token", baseUrl: "https://idx.test", organizationId: "org_idx" })
    expect(hasSaeeolIndexingAuth({ config: { indexing: { saeeol: { apiKey: "idx-token" } } } })).toBe(true)
  })

  test("detects auth from provider config, provider state, auth storage, and env", () => {
    expect(
      resolveSaeeolIndexingAuth({ config: { provider: { saeeol: { options: { apiKey: "cfg-token" } } } } }).apiKey,
    ).toBe("cfg-token")
    expect(resolveSaeeolIndexingAuth({ provider: { options: { saeeolToken: "provider-token" } } }).apiKey).toBe(
      "provider-token",
    )
    expect(resolveSaeeolIndexingAuth({ auth: { type: "oauth", access: "oauth-token", accountId: "org_oauth" } })).toEqual(
      {
        apiKey: "oauth-token",
        organizationId: "org_oauth",
      },
    )
    expect(resolveSaeeolIndexingAuth({ env: { SAEEOL_API_KEY: "env-token", SAEEOL_ORG_ID: "org_env" } })).toEqual({
      apiKey: "env-token",
      organizationId: "org_env",
    })
  })

  test("defaults to Saeeol only when no provider or other embedder config is present", () => {
    const auth = { apiKey: "saeeol-token" }

    expect(shouldDefaultIndexingToSaeeol({}, auth)).toBe(true)
    expect(shouldDefaultIndexingToSaeeol({ provider: "openai" }, auth)).toBe(false)
    expect(shouldDefaultIndexingToSaeeol({ openai: { apiKey: "openai-key" } }, auth)).toBe(false)
    expect(shouldDefaultIndexingToSaeeol({ ollama: { baseUrl: "http://localhost:11434" } }, auth)).toBe(false)
  })
})
