import { LEAKY_AI_ERRORS, buildRetryError, findPlantedContent } from "@/lib/ai/__mocks__/leaky-ai-errors";
import { beforeEach, describe, expect, test, vi } from "vitest";
import { z } from "zod";
import { OperationNotAllowedError, ResourceNotFoundError } from "@formbricks/types/errors";
import {
  assertOrganizationAIConfigured,
  generateOrganizationAIObject,
  generateOrganizationAIText,
  getAISmartToolsUnavailableReason,
  getOrganizationAIConfig,
  isInstanceAIConfigured,
  streamOrganizationAIObject,
} from "./service";

const mocks = vi.hoisted(() => ({
  generateObject: vi.fn(),
  streamObject: vi.fn(),
  generateText: vi.fn(),
  isAiConfigured: vi.fn(),
  classifyAIProviderError: vi.fn(),
  getOrganization: vi.fn(),
  getIsAISmartToolsEnabled: vi.fn(),
  loggerError: vi.fn(),
  loggerWarn: vi.fn(),
  wrapAiModelWithTracing: vi.fn(),
}));

vi.mock("server-only", () => ({}));

vi.mock("@formbricks/ai", async (importOriginal) => ({
  // Real: the service and its log helper only check `instanceof` against it.
  AIOAuthTokenError: (await importOriginal<typeof import("@formbricks/ai")>()).AIOAuthTokenError,
  AIConfigurationError: class AIConfigurationError extends Error {
    code: string;
    details: Record<string, unknown>;

    constructor(code: string, message: string, details: Record<string, unknown> = {}) {
      super(message);
      this.name = "AIConfigurationError";
      this.code = code;
      this.details = details;
    }
  },
  AIOutputTokenLimitError: class AIOutputTokenLimitError extends Error {
    details: Record<string, number>;

    constructor(details: Record<string, number> = {}) {
      super("AI generation stopped because the output token limit was reached");
      this.name = "AIOutputTokenLimitError";
      this.details = details;
    }
  },
  generateObject: mocks.generateObject,
  streamObject: mocks.streamObject,
  generateText: mocks.generateText,
  isAiConfigured: mocks.isAiConfigured,
  classifyAIProviderError: mocks.classifyAIProviderError,
}));

vi.mock("@formbricks/logger", () => ({
  logger: {
    error: mocks.loggerError,
    warn: mocks.loggerWarn,
  },
}));

vi.mock("@/lib/env", () => ({
  env: {
    AI_PROVIDER: "google",
    AI_MODEL: "gemini-2.5-flash",
    AI_GOOGLE_CLOUD_PROJECT: "google-cloud-project",
    AI_GOOGLE_CLOUD_LOCATION: "us-central1",
    AI_GOOGLE_CLOUD_CREDENTIALS_JSON: undefined,
    AI_GOOGLE_CLOUD_APPLICATION_CREDENTIALS: "/tmp/google-cloud.json",
    AI_AWS_REGION: "us-east-1",
    AI_AWS_ACCESS_KEY_ID: "aws-access-key-id",
    AI_AWS_SECRET_ACCESS_KEY: "aws-secret-access-key",
    AI_AWS_SESSION_TOKEN: undefined,
    AI_AZURE_BASE_URL: "https://example-resource.openai.azure.com/openai",
    AI_AZURE_RESOURCE_NAME: undefined,
    AI_AZURE_API_KEY: "azure-api-key",
    AI_AZURE_API_VERSION: "v1",
  },
}));

vi.mock("@/lib/organization/service", () => ({
  getOrganization: mocks.getOrganization,
}));

vi.mock("@/modules/ee/license-check/lib/utils", () => ({
  getIsAISmartToolsEnabled: mocks.getIsAISmartToolsEnabled,
}));

vi.mock("@/lib/posthog/ai-tracing", () => ({
  wrapAiModelWithTracing: mocks.wrapAiModelWithTracing,
}));

describe("AI organization service", () => {
  beforeEach(() => {
    vi.clearAllMocks();

    mocks.isAiConfigured.mockReturnValue(true);
    mocks.classifyAIProviderError.mockReturnValue(undefined);
    mocks.getOrganization.mockResolvedValue({
      id: "org_1",
      isAISmartToolsEnabled: true,
    });
    mocks.getIsAISmartToolsEnabled.mockResolvedValue(true);
  });

  test("returns the instance AI status and organization settings", async () => {
    const configured = isInstanceAIConfigured();
    const result = await getOrganizationAIConfig("org_1");

    expect(configured).toBe(true);
    expect(result).toMatchObject({
      organizationId: "org_1",
      isAISmartToolsEnabled: true,
      isAISmartToolsEntitled: true,
      isInstanceConfigured: true,
    });
  });

  test("throws when the organization cannot be found", async () => {
    mocks.getOrganization.mockResolvedValueOnce(null);

    await expect(getOrganizationAIConfig("org_missing")).rejects.toThrow(ResourceNotFoundError);
  });

  test("fails closed when the organization is not entitled to AI", async () => {
    mocks.getIsAISmartToolsEnabled.mockResolvedValueOnce(false);

    await expect(assertOrganizationAIConfigured("org_1")).rejects.toThrow(OperationNotAllowedError);
  });

  test("fails closed when the requested AI capability is disabled", async () => {
    mocks.getOrganization.mockResolvedValueOnce({
      id: "org_1",
      isAISmartToolsEnabled: false,
    });

    await expect(assertOrganizationAIConfigured("org_1")).rejects.toThrow(OperationNotAllowedError);
  });

  test("fails closed when the instance AI configuration is incomplete", async () => {
    mocks.isAiConfigured.mockReturnValueOnce(false);

    await expect(assertOrganizationAIConfigured("org_1")).rejects.toThrow(OperationNotAllowedError);
  });

  test("generates organization AI text with the configured package abstraction", async () => {
    const generatedText = { text: "Translated text" };
    mocks.generateText.mockResolvedValueOnce(generatedText);

    const result = await generateOrganizationAIText({
      organizationId: "org_1",
      prompt: "Translate this survey",
    });

    expect(result).toBe(generatedText);
    expect(mocks.generateText).toHaveBeenCalledWith(
      {
        prompt: "Translate this survey",
      },
      expect.objectContaining({
        AI_PROVIDER: "google",
        AI_MODEL: "gemini-2.5-flash",
        AI_GOOGLE_CLOUD_PROJECT: "google-cloud-project",
      }),
      undefined
    );
  });

  test("wraps the model with PostHog tracing when aiTracing is provided (text)", async () => {
    mocks.generateText.mockResolvedValueOnce({ text: "Translated text" });

    await generateOrganizationAIText({
      organizationId: "org_1",
      aiTracing: { distinctId: "user_1", feature: "ai_survey_generation" },
      prompt: "Translate this survey",
    });

    const wrapModel = mocks.generateText.mock.calls[0][2];
    expect(wrapModel).toBeInstanceOf(Function);

    const rawModel = { providerName: "google" };
    wrapModel(rawModel);
    expect(mocks.wrapAiModelWithTracing).toHaveBeenCalledWith(rawModel, {
      organizationId: "org_1",
      distinctId: "user_1",
      feature: "ai_survey_generation",
    });
  });

  test("generates organization AI objects with the configured package abstraction", async () => {
    const generatedObject = { object: { name: "Generated survey" } };
    const schema = { type: "object" };
    mocks.generateObject.mockResolvedValueOnce(generatedObject);

    const result = await generateOrganizationAIObject<{ name: string }>({
      organizationId: "org_1",
      schema,
      prompt: "Generate a survey",
    } as unknown as Parameters<typeof generateOrganizationAIObject<{ name: string }>>[0]);

    expect(result).toBe(generatedObject);
    expect(mocks.generateObject).toHaveBeenCalledWith(
      {
        schema,
        prompt: "Generate a survey",
      },
      expect.objectContaining({
        AI_PROVIDER: "google",
        AI_MODEL: "gemini-2.5-flash",
        AI_GOOGLE_CLOUD_PROJECT: "google-cloud-project",
      }),
      undefined
    );
  });

  test("wraps the model with PostHog tracing when aiTracing is provided (object)", async () => {
    mocks.generateObject.mockResolvedValueOnce({ object: { name: "Generated survey" } });

    await generateOrganizationAIObject({
      organizationId: "org_1",
      aiTracing: { distinctId: "user_1", feature: "ai_chart_query", workspaceId: "ws_1" },
      schema: { type: "object" },
      prompt: "Generate a survey",
    } as unknown as Parameters<typeof generateOrganizationAIObject>[0]);

    const wrapModel = mocks.generateObject.mock.calls[0][2];
    expect(wrapModel).toBeInstanceOf(Function);

    const rawModel = { providerName: "google" };
    wrapModel(rawModel);
    expect(mocks.wrapAiModelWithTracing).toHaveBeenCalledWith(rawModel, {
      organizationId: "org_1",
      distinctId: "user_1",
      feature: "ai_chart_query",
      workspaceId: "ws_1",
    });
  });

  test("logs generation errors by name and frames, never the message, and rethrows them", async () => {
    const modelError = new Error("provider boom");
    mocks.generateText.mockRejectedValueOnce(modelError);

    await expect(
      generateOrganizationAIText({
        organizationId: "org_1",
        prompt: "Translate this survey",
      })
    ).rejects.toThrow(modelError);
    expect(mocks.loggerError).toHaveBeenCalledWith(
      {
        organizationId: "org_1",
        isInstanceConfigured: true,
        errorCode: undefined,
        statusCode: undefined,
        isQuotaExhausted: undefined,
        isRetryable: undefined,
        isAuthFailure: undefined,
        errName: "Error",
        errStack: expect.stringMatching(/^ +at \S.*(?:\n +at \S.*)*$/),
      },
      "Failed to generate organization AI text"
    );
  });

  test("logs object generation errors by name and frames, never the message, and rethrows them", async () => {
    const modelError = new Error("provider boom");
    mocks.generateObject.mockRejectedValueOnce(modelError);

    await expect(
      generateOrganizationAIObject({
        organizationId: "org_1",
        schema: { type: "object" },
        prompt: "Generate a survey",
      } as unknown as Parameters<typeof generateOrganizationAIObject>[0])
    ).rejects.toThrow(modelError);
    expect(mocks.loggerError).toHaveBeenCalledWith(
      {
        organizationId: "org_1",
        isInstanceConfigured: true,
        errorCode: undefined,
        statusCode: undefined,
        isQuotaExhausted: undefined,
        isRetryable: undefined,
        isAuthFailure: undefined,
        errName: "Error",
        errStack: expect.stringMatching(/^ +at \S.*(?:\n +at \S.*)*$/),
      },
      "Failed to generate organization AI object"
    );
  });

  // ENG-2831: every caller maps a token-limit overflow to a user-facing message, so it must not log at
  // error level — but the token counts still have to reach the logs.
  test("warns with the token counts instead of logging an error when the output token limit is hit", async () => {
    const { AIOutputTokenLimitError } = await import("@formbricks/ai");
    const details = { maxOutputTokens: 8192, outputTokens: 8192, reasoningTokens: 512 };
    const tokenLimitError = new AIOutputTokenLimitError(details);
    mocks.generateObject.mockRejectedValueOnce(tokenLimitError);

    await expect(
      generateOrganizationAIObject({
        organizationId: "org_1",
        schema: { type: "object" },
        prompt: "Translate this survey",
      } as unknown as Parameters<typeof generateOrganizationAIObject>[0])
    ).rejects.toBe(tokenLimitError);
    expect(mocks.loggerError).not.toHaveBeenCalled();
    expect(mocks.loggerWarn).toHaveBeenCalledWith(
      { organizationId: "org_1", ...details },
      "Failed to generate organization AI object: output token limit reached"
    );
  });

  test("warns rather than logging an error when a call runs out of its own timeout, with the same fields", async () => {
    const timeoutError = new DOMException("The operation timed out.", "TimeoutError");
    mocks.generateObject.mockRejectedValueOnce(timeoutError);

    await expect(
      generateOrganizationAIObject({
        organizationId: "org_1",
        schema: z.object({}),
        prompt: "Plan this import",
        timeout: 45_000,
      })
    ).rejects.toBe(timeoutError);
    expect(mocks.loggerError).not.toHaveBeenCalled();
    expect(mocks.loggerWarn).toHaveBeenCalledWith(
      expect.objectContaining({
        organizationId: "org_1",
        isInstanceConfigured: true,
        errName: "TimeoutError",
      }),
      "Failed to generate organization AI object"
    );
    expect(JSON.stringify(mocks.loggerWarn.mock.calls)).not.toContain("The operation timed out.");
  });

  test("does not log an abort when the caller's own signal fired, even with a timeout set", async () => {
    const controller = new AbortController();
    controller.abort();
    const abortError = new DOMException("This operation was aborted", "AbortError");
    mocks.generateObject.mockRejectedValueOnce(abortError);

    await expect(
      generateOrganizationAIObject({
        organizationId: "org_1",
        schema: z.object({}),
        prompt: "Plan this import",
        timeout: 45_000,
        abortSignal: controller.signal,
      })
    ).rejects.toBe(abortError);
    expect(mocks.loggerError).not.toHaveBeenCalled();
    expect(mocks.loggerWarn).not.toHaveBeenCalled();
  });

  test("warns about an abort the caller did not make: its timeout firing during the SDK's retry backoff", async () => {
    const abortError = new DOMException("Delay was aborted", "AbortError");
    mocks.generateObject.mockRejectedValueOnce(abortError);

    await expect(
      generateOrganizationAIObject({
        organizationId: "org_1",
        schema: z.object({}),
        prompt: "Plan this import",
        timeout: 45_000,
        abortSignal: new AbortController().signal,
      })
    ).rejects.toBe(abortError);
    expect(mocks.loggerError).not.toHaveBeenCalled();
    expect(mocks.loggerWarn).toHaveBeenCalledWith(
      expect.objectContaining({ organizationId: "org_1", errName: "AbortError" }),
      "Failed to generate organization AI object"
    );
    expect(JSON.stringify(mocks.loggerWarn.mock.calls)).not.toContain("Delay was aborted");
  });

  test("converts a provider 429 from text generation into a TooManyRequestsError", async () => {
    const quotaError = new Error("Resource exhausted");
    mocks.generateText.mockRejectedValueOnce(quotaError);
    mocks.classifyAIProviderError.mockReturnValueOnce({
      isQuotaExhausted: true,
      isRetryable: true,
      statusCode: 429,
    });

    await expect(
      generateOrganizationAIText({ organizationId: "org_1", prompt: "Translate this survey" })
    ).rejects.toMatchObject({ name: "TooManyRequestsError", message: "ai_quota_exceeded" });
  });

  test("converts a provider 429 into a TooManyRequestsError with the quota code", async () => {
    const quotaError = new Error("Resource exhausted");
    mocks.generateObject.mockRejectedValueOnce(quotaError);
    mocks.classifyAIProviderError.mockReturnValueOnce({
      isQuotaExhausted: true,
      isRetryable: true,
      statusCode: 429,
      retryAfterSeconds: 30,
    });

    await expect(
      generateOrganizationAIObject({
        organizationId: "org_1",
        schema: { type: "object" },
        prompt: "Generate a survey",
      } as unknown as Parameters<typeof generateOrganizationAIObject>[0])
    ).rejects.toMatchObject({ name: "TooManyRequestsError", message: "ai_quota_exceeded", retryAfter: 30 });

    expect(mocks.loggerError).toHaveBeenCalledWith(
      expect.objectContaining({ statusCode: 429, isQuotaExhausted: true, isRetryable: true }),
      "Failed to generate organization AI object"
    );
  });

  test("rethrows non-quota provider errors unchanged", async () => {
    const serverError = new Error("provider 500");
    mocks.generateObject.mockRejectedValueOnce(serverError);
    mocks.classifyAIProviderError.mockReturnValueOnce({
      isQuotaExhausted: false,
      isRetryable: true,
      statusCode: 500,
    });

    await expect(
      generateOrganizationAIObject({
        organizationId: "org_1",
        schema: { type: "object" },
        prompt: "Generate a survey",
      } as unknown as Parameters<typeof generateOrganizationAIObject>[0])
    ).rejects.toBe(serverError);
  });

  describe("a caller that retries itself (`maxRetries: 0`)", () => {
    const failWith = async (
      statusCode: number,
      isRetryable: boolean,
      maxRetries: number | undefined,
      isAuthFailure = false
    ) => {
      const providerError = new Error(`provider ${statusCode}`);
      mocks.generateObject.mockRejectedValueOnce(providerError);
      mocks.classifyAIProviderError.mockReturnValue({
        isQuotaExhausted: false,
        isRetryable,
        isAuthFailure,
        statusCode,
      });
      await expect(
        generateOrganizationAIObject({
          organizationId: "org_1",
          schema: z.object({}),
          prompt: "Plan this import",
          timeout: 45_000,
          ...(maxRetries === undefined ? {} : { maxRetries }),
        })
      ).rejects.toBe(providerError);
    };

    test("warns about a retryable failure: one attempt of its own retry policy is not an incident", async () => {
      await failWith(503, true, 0);

      expect(mocks.loggerError).not.toHaveBeenCalled();
      expect(mocks.loggerWarn).toHaveBeenCalledWith(
        expect.objectContaining({ organizationId: "org_1", statusCode: 503, isRetryable: true }),
        "Failed to generate organization AI object"
      );
      expect(JSON.stringify(mocks.loggerWarn.mock.calls)).not.toContain("provider 503");
    });

    test("still logs a failure it will not retry as an error", async () => {
      await failWith(401, false, 0, true);

      expect(mocks.loggerWarn).not.toHaveBeenCalled();
      expect(mocks.loggerError).toHaveBeenCalledWith(
        expect.objectContaining({ statusCode: 401, isAuthFailure: true }),
        "Failed to generate organization AI object"
      );
    });

    test("leaves a caller that keeps the SDK's retries as it was: a 503 is an error", async () => {
      await failWith(503, true, undefined);

      expect(mocks.loggerWarn).not.toHaveBeenCalled();
      expect(mocks.loggerError).toHaveBeenCalledWith(
        expect.objectContaining({ statusCode: 503 }),
        "Failed to generate organization AI object"
      );
    });
  });

  // Casts rather than `any`: `@formbricks/ai` is mocked here, so the schema is never read — but the input
  // types still require a real one.
  const objectInput = () =>
    ({
      organizationId: "org_1",
      schema: { type: "object" },
      prompt: "Generate a survey",
    }) as unknown as Parameters<typeof generateOrganizationAIObject>[0];

  const streamInput = () =>
    ({ organizationId: "org_1", prompt: "Generate", schema: { type: "object" } }) as unknown as Parameters<
      typeof streamOrganizationAIObject
    >[0];

  const streamResult = (completion: Promise<unknown>) => {
    // The service hands this promise back untouched; keep it handled so a rejection asserted on
    // later does not surface as an unhandled rejection first.
    completion.catch(() => undefined);
    return { partialObjectStream: {}, completion };
  };

  test("logs which part of the AI configuration is wrong by field name, never the message", async () => {
    const { AIConfigurationError } = await import("@formbricks/ai");
    const configurationError = new AIConfigurationError(
      "providerNotConfigured",
      "AWS Bedrock credentials are incomplete",
      { provider: "aws", missingFields: ["AI_AWS_REGION"] }
    );
    mocks.generateObject.mockRejectedValueOnce(configurationError);

    await expect(generateOrganizationAIObject(objectInput())).rejects.toBe(configurationError);

    const [logged] = mocks.loggerError.mock.calls[0];
    expect(logged).toMatchObject({
      errorCode: "providerNotConfigured",
      configuration: { provider: "aws", missingFields: ["AI_AWS_REGION"] },
      errName: "AIConfigurationError",
    });
    expect(JSON.stringify(logged)).not.toContain("credentials are incomplete");
  });

  // ENG-3720: an AI SDK error carries the prompt (`requestBodyValues`, once per retry attempt) and the
  // model's output (`text`, `value`, and the messages built from them). The failure log must locate and
  // classify the failure without any of it — and the caller still gets the original error to branch on.
  describe("never logs what the AI call carried", () => {
    beforeEach(async () => {
      const actual = await vi.importActual<typeof import("@formbricks/ai")>("@formbricks/ai");
      mocks.classifyAIProviderError.mockImplementation(actual.classifyAIProviderError);
    });

    const expectCleanFailureLog = (error: Error) => {
      expect(mocks.loggerError).toHaveBeenCalledTimes(1);
      expect(mocks.loggerError.mock.calls[0][0]).toMatchObject({
        organizationId: "org_1",
        errName: error.name,
        errStack: expect.stringMatching(/^ +at \S.*(?:\n +at \S.*)*$/),
      });
      expect(findPlantedContent([mocks.loggerError.mock.calls, mocks.loggerWarn.mock.calls])).toBeUndefined();
    };

    test.each(LEAKY_AI_ERRORS)("text generation failing with %s", async (_, build) => {
      const error = build();
      mocks.generateText.mockRejectedValueOnce(error);

      await expect(
        generateOrganizationAIText({ organizationId: "org_1", prompt: "Translate this survey" })
      ).rejects.toBe(error);
      expectCleanFailureLog(error);
    });

    test.each(LEAKY_AI_ERRORS)("object generation failing with %s", async (_, build) => {
      const error = build();
      mocks.generateObject.mockRejectedValueOnce(error);

      await expect(generateOrganizationAIObject(objectInput())).rejects.toBe(error);
      expectCleanFailureLog(error);
    });

    test.each(LEAKY_AI_ERRORS)("a streamed generation whose completion fails with %s", async (_, build) => {
      const error = build();
      mocks.streamObject.mockReturnValueOnce(streamResult(Promise.reject(error)));

      const result = await streamOrganizationAIObject(streamInput());

      await expect(result.completion).rejects.toBe(error);
      expectCleanFailureLog(error);
    });

    test("keeps the provider status and the retry outcome in the log", async () => {
      mocks.generateObject.mockRejectedValueOnce(buildRetryError());

      await expect(generateOrganizationAIObject(objectInput())).rejects.toThrow();

      expect(mocks.loggerError.mock.calls[0][0]).toMatchObject({
        statusCode: 500,
        isRetryable: true,
        retryReason: "maxRetriesExceeded",
        retryAttempts: 3,
        lastErrName: "AI_APICallError",
      });
    });
  });

  describe("streamOrganizationAIObject", () => {
    test("a cancelled generation is not an error: no error log, and the rejection is untouched", async () => {
      // Stop and tab-close both land here. Logging them at error level pages someone for a user
      // doing exactly what the button offers.
      const abortError = new Error("The operation was aborted");
      abortError.name = "AbortError";
      mocks.streamObject.mockReturnValueOnce(streamResult(Promise.reject(abortError)));

      const result = await streamOrganizationAIObject(streamInput());

      await expect(result.completion).rejects.toBe(abortError);
      expect(mocks.loggerError).not.toHaveBeenCalled();
      expect(mocks.classifyAIProviderError).not.toHaveBeenCalled();
    });

    test("an abort wrapped as a cause is recognised too", async () => {
      const abortError = new Error("The operation was aborted");
      abortError.name = "AbortError";
      const wrapped = new Error("stream failed", { cause: abortError });
      mocks.streamObject.mockReturnValueOnce(streamResult(Promise.reject(wrapped)));

      const result = await streamOrganizationAIObject(streamInput());

      await expect(result.completion).rejects.toBe(wrapped);
      expect(mocks.loggerError).not.toHaveBeenCalled();
    });

    test("a real provider failure still logs and maps a 429", async () => {
      const quotaError = new Error("Resource exhausted");
      mocks.classifyAIProviderError.mockReturnValueOnce({
        statusCode: 429,
        isQuotaExhausted: true,
        isRetryable: true,
        retryAfterSeconds: 30,
      });
      mocks.streamObject.mockReturnValueOnce(streamResult(Promise.reject(quotaError)));

      const result = await streamOrganizationAIObject(streamInput());

      await expect(result.completion).rejects.toMatchObject({
        name: "TooManyRequestsError",
        message: "ai_quota_exceeded",
        retryAfter: 30,
      });
      expect(mocks.loggerError).toHaveBeenCalled();
    });
  });

  describe("getAISmartToolsUnavailableReason", () => {
    const baseConfig = {
      organizationId: "org_1",
      isAISmartToolsEntitled: true,
      isAISmartToolsEnabled: true,
      isInstanceConfigured: true,
    };

    test("returns undefined when all checks pass", () => {
      expect(getAISmartToolsUnavailableReason(baseConfig)).toBeUndefined();
    });

    test("returns not_in_plan when smart tools entitlement is missing", () => {
      expect(getAISmartToolsUnavailableReason({ ...baseConfig, isAISmartToolsEntitled: false })).toBe(
        "not_in_plan"
      );
    });

    test("returns not_enabled when smart tools is disabled at org level", () => {
      expect(getAISmartToolsUnavailableReason({ ...baseConfig, isAISmartToolsEnabled: false })).toBe(
        "not_enabled"
      );
    });

    test("returns instance_not_configured when instance AI is missing", () => {
      expect(getAISmartToolsUnavailableReason({ ...baseConfig, isInstanceConfigured: false })).toBe(
        "instance_not_configured"
      );
    });
  });
});
