import { SystemRole } from "@capakraken/shared";
import { describe, expect, it, vi } from "vitest";
import { settingsRouter } from "../router/settings.js";
import { createCallerFactory } from "../trpc.js";

function createProtectedContext(
  db: Record<string, unknown>,
  systemRole: SystemRole,
) {
  return {
    session: {
      user: { email: "user@example.com", name: "User", image: null },
      expires: "2099-01-01T00:00:00.000Z",
    },
    db: db as never,
    dbUser: {
      id: "user_1",
      systemRole,
      permissionOverrides: null,
    },
  };
}

describe("settings router authorization", () => {
  it("forbids non-admin users from reading AI configuration status", async () => {
    const findUnique = vi.fn();
    const caller = createCallerFactory(settingsRouter)(createProtectedContext({
      systemSettings: {
        findUnique,
      },
    }, SystemRole.USER));

    await expect(caller.getAiConfigured()).rejects.toMatchObject({
      code: "FORBIDDEN",
      message: "Admin role required",
    });

    expect(findUnique).not.toHaveBeenCalled();
  });

  it("allows admins to read AI configuration status", async () => {
    const findUnique = vi.fn().mockResolvedValue({
      aiProvider: "azure",
      azureOpenAiEndpoint: "https://example.openai.azure.com",
      azureOpenAiDeployment: "gpt-4o",
      azureOpenAiApiKey: "secret",
    });
    const caller = createCallerFactory(settingsRouter)(createProtectedContext({
      systemSettings: {
        findUnique,
      },
    }, SystemRole.ADMIN));

    const result = await caller.getAiConfigured();

    expect(result).toEqual({ configured: true });
    expect(findUnique).toHaveBeenCalledWith({
      where: { id: "singleton" },
      select: {
        aiProvider: true,
        azureOpenAiEndpoint: true,
        azureOpenAiDeployment: true,
        azureOpenAiApiKey: true,
      },
    });
  });
});
