import { describe, expect, it } from "vitest";
import { resolveProviderRuntimeEnv } from "../src/dimsdk/core/provider-runtime-env.ts";

describe("provider runtime env", () => {
  it("resolves next api oauth env updates from the active connection", () => {
    const resolved = resolveProviderRuntimeEnv({
      providerId: "next-api-oauth",
      legacyCustomProviderName: "Custom Provider",
      providerState: {
        connections: {
          "next-api-oauth": {
            apiKey: "next-token",
            baseUrl: "https://relay.example/v1",
          },
        },
      },
      config: {},
      env: {},
    });

    expect(resolved).toMatchObject({
      config: {
        apiKey: "next-token",
        baseUrl: "https://relay.example/v1",
      },
      updates: {
        DIMCODE_PROVIDER_ADAPTER: "openai",
        DIMCODE_PROVIDER_ID: "next-api-oauth",
        DIMCODE_OPENAI_BASE_URL: "https://relay.example/v1",
        OPENAI_BASE_URL: "https://relay.example/v1",
        OPENAI_API_KEY: "next-token",
      },
    });
    expect(resolved?.updates.DIMCODE_USE_NEXT_API_OAUTH).toBeUndefined();
    expect(resolved?.updates.DIMCODE_CCMOCK).toBeUndefined();
  });

  it("maps the google provider into gemini runtime env keys", () => {
    const resolved = resolveProviderRuntimeEnv({
      providerId: "google",
      legacyCustomProviderName: "Custom Provider",
      providerState: {
        connections: {
          google: {
            apiKey: "google-key",
            baseUrl: "https://generativelanguage.googleapis.com",
          },
        },
      },
      config: {},
      env: {},
    });

    expect(resolved?.updates).toMatchObject({
      DIMCODE_PROVIDER_ADAPTER: "gemini",
      DIMCODE_PROVIDER_ID: "google",
      DIMCODE_GEMINI_BASE_URL: "https://generativelanguage.googleapis.com",
      GOOGLE_API_KEY: "google-key",
    });
    expect(resolved?.updates.OPENAI_API_KEY).toBeUndefined();
    expect(resolved?.updates.DIMCODE_USE_NEXT_API_OAUTH).toBeUndefined();
  });

  it("maps custom providers through their adapter-specific runtime env keys", () => {
    const resolved = resolveProviderRuntimeEnv({
      providerId: "cp_gateway",
      legacyCustomProviderName: "Custom Provider",
      providerState: {
        connections: {},
        customProviders: [
          {
            id: "cp_gateway",
            name: "Gateway",
            adapter: "anthropic",
            apiKey: "custom-key",
            baseUrl: "https://anthropic.example/v1",
            models: [],
          },
        ],
        custom: { models: [] },
      },
      config: {},
      env: {},
    });

    expect(resolved?.updates).toMatchObject({
      DIMCODE_PROVIDER_ADAPTER: "anthropic",
      DIMCODE_PROVIDER_ID: "cp_gateway",
      DIMCODE_PROVIDER_NAME: "Gateway",
      DIMCODE_ANTHROPIC_BASE_URL: "https://anthropic.example/v1",
      ANTHROPIC_API_KEY: "custom-key",
    });
    expect(resolved?.updates.OPENAI_API_KEY).toBeUndefined();
  });
});
