import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { DEFAULT_OPENAI_MODEL, SystemRole } from "@capakraken/shared";

import {
  createToolContext,
  executeTool,
  generateGeminiImage,
  testSmtpConnection,
} from "./assistant-tools-settings-test-helpers.js";

describe("assistant settings tools connection checks", () => {
  beforeEach(() => {
    vi.clearAllMocks();
  });

  afterEach(() => {
    vi.unstubAllGlobals();
    vi.unstubAllEnvs();
  });

  it("tests the AI connection through the real settings router path", async () => {
    vi.stubEnv("OPENAI_API_KEY", "env-openai-key");
    const fetch = vi.fn().mockResolvedValue({
      ok: true,
      text: vi.fn().mockResolvedValue("ok"),
    });
    vi.stubGlobal("fetch", fetch);

    const ctx = createToolContext({
      systemSettings: {
        findUnique: vi.fn().mockResolvedValue({
          aiProvider: "openai",
          azureOpenAiDeployment: DEFAULT_OPENAI_MODEL,
          azureOpenAiApiKey: null,
        }),
      },
    });

    const result = await executeTool("test_ai_connection", JSON.stringify({}), ctx);

    expect(JSON.parse(result.content)).toEqual({ ok: true });
    expect(fetch).toHaveBeenCalledWith(
      "https://api.openai.com/v1/chat/completions",
      expect.objectContaining({
        headers: expect.objectContaining({
          Authorization: "Bearer env-openai-key",
        }),
      }),
    );
  });

  it("tests the SMTP connection through the real settings router path", async () => {
    vi.mocked(testSmtpConnection).mockResolvedValue({ ok: true });

    const ctx = createToolContext({});
    const result = await executeTool("test_smtp_connection", JSON.stringify({}), ctx);

    expect(JSON.parse(result.content)).toEqual({ ok: true });
    expect(testSmtpConnection).toHaveBeenCalledTimes(1);
  });

  it("tests the Gemini connection through the real settings router path", async () => {
    vi.mocked(generateGeminiImage).mockResolvedValue("data:image/png;base64,abc123");

    const ctx = createToolContext({
      systemSettings: {
        findUnique: vi.fn().mockResolvedValue({
          geminiApiKey: "gemini-key",
          geminiModel: "gemini-2.5-flash-image",
        }),
      },
    });

    const result = await executeTool("test_gemini_connection", JSON.stringify({}), ctx);
    const parsed = JSON.parse(result.content) as {
      ok: boolean;
      model: string;
      preview: string;
    };

    expect(parsed.ok).toBe(true);
    expect(parsed.model).toBe("gemini-2.5-flash-image");
    expect(parsed.preview).toContain("data:image/png;base64,abc123");
    expect(generateGeminiImage).toHaveBeenCalledWith(
      "gemini-key",
      "A simple blue circle on white background, minimal, 256x256",
      "gemini-2.5-flash-image",
    );
  });

  it("rejects admin-only connection tools for non-admin assistant users", async () => {
    const ctx = createToolContext(
      {
        systemSettings: {
          findUnique: vi.fn(),
        },
      },
      SystemRole.MANAGER,
    );

    for (const toolName of [
      "test_ai_connection",
      "test_smtp_connection",
      "test_gemini_connection",
    ] as const) {
      const result = await executeTool(toolName, JSON.stringify({}), ctx);
      expect(JSON.parse(result.content)).toEqual({
        error: "You do not have permission to perform this action.",
      });
    }
  });
});
