import { describe, it, expect, beforeEach, vi } from 'vitest';

const { getCurrentUserMock } = vi.hoisted(() => ({
  getCurrentUserMock: vi.fn(),
}));
vi.mock('@/lib/auth', async (orig) => {
  const actual = (await orig()) as Record<string, unknown>;
  return { ...actual, getCurrentUser: getCurrentUserMock };
});

import { NextRequest } from 'next/server';
import { prisma } from '@/lib/prisma';
import { POST as createConfig } from '@/app/api/ai/configs/route';
import { POST as testConfig } from '@/app/api/ai/test/route';
import { GET as ollamaModels } from '@/app/api/ai/ollama/models/route';

// Custom-URL providers (Ollama / OpenAI-compatible) are admin-only — a
// non-admin pointing the server at an arbitrary URL is the SSRF actor vector
// (EVALUATION.md P1). Fixed-URL cloud providers (claude/openai/gemini) stay
// per-user. These tests lock that boundary.

function jsonReq(url: string, body: unknown): NextRequest {
  return new NextRequest(url, {
    method: 'POST',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify(body),
  } as ConstructorParameters<typeof NextRequest>[1]);
}

async function makeUser(email: string, isAdmin: boolean) {
  return prisma.user.create({
    data: { email, passwordHash: 'fake', isAdmin },
  });
}

beforeEach(async () => {
  await prisma.aIConfigProfile.deleteMany();
  await prisma.userPreferences.deleteMany();
  await prisma.user.deleteMany();
  getCurrentUserMock.mockReset();
});

describe('POST /api/ai/configs — custom-URL providers are admin-only', () => {
  it('rejects a non-admin creating an ollama (custom-URL) config', async () => {
    const u = await makeUser('u@x.com', false);
    getCurrentUserMock.mockResolvedValue(u);
    const res = await createConfig(
      jsonReq('http://x/api/ai/configs', {
        provider: 'ollama',
        model: 'llama3',
        baseUrl: 'http://ollama.startos:11434',
      }),
    );
    expect(res.status).toBe(403);
  });

  it('rejects a non-admin supplying a baseUrl with any provider', async () => {
    const u = await makeUser('u2@x.com', false);
    getCurrentUserMock.mockResolvedValue(u);
    const res = await createConfig(
      jsonReq('http://x/api/ai/configs', {
        provider: 'openai',
        model: 'gpt-4o',
        baseUrl: 'http://169.254.169.254',
      }),
    );
    expect(res.status).toBe(403);
  });

  it('allows a non-admin creating a fixed-URL cloud config (claude)', async () => {
    const u = await makeUser('u3@x.com', false);
    getCurrentUserMock.mockResolvedValue(u);
    const res = await createConfig(
      jsonReq('http://x/api/ai/configs', {
        provider: 'claude',
        model: 'claude-sonnet-4-6',
        apiKey: 'sk-test',
      }),
    );
    expect(res.status).toBe(200);
  });

  it('allows an admin creating an ollama config', async () => {
    const a = await makeUser('admin@x.com', true);
    getCurrentUserMock.mockResolvedValue(a);
    const res = await createConfig(
      jsonReq('http://x/api/ai/configs', {
        provider: 'ollama',
        model: 'llama3',
        baseUrl: 'http://ollama.startos:11434',
      }),
    );
    expect(res.status).toBe(200);
  });
});

describe('POST /api/ai/test — testing a custom base URL is admin-only', () => {
  it('rejects a non-admin testing an openai-compatible draft', async () => {
    getCurrentUserMock.mockResolvedValue({ id: 'u', email: 'u@x.com', isAdmin: false });
    const res = await testConfig(
      jsonReq('http://x/api/ai/test', {
        provider: 'openai-compatible',
        model: 'x',
        baseUrl: 'http://192.168.0.1',
        apiKey: 'k',
      }),
    );
    expect(res.status).toBe(403);
  });
});

describe('GET /api/ai/ollama/models — admin-only', () => {
  it('returns 403 for a non-admin', async () => {
    getCurrentUserMock.mockResolvedValue({ id: 'u', email: 'u@x.com', isAdmin: false });
    const res = await ollamaModels(
      new NextRequest('http://x/api/ai/ollama/models?baseUrl=http://192.168.0.1'),
    );
    expect(res.status).toBe(403);
  });

  it('returns 401 when unauthenticated', async () => {
    getCurrentUserMock.mockResolvedValue(null);
    const res = await ollamaModels(new NextRequest('http://x/api/ai/ollama/models'));
    expect(res.status).toBe(401);
  });
});
