/**
 * Tests for GET /api/audit
 *
 * Covers:
 * - 401 when unauthenticated
 * - 200 with entries list and total (default mode)
 * - 200 with summary (total + failedLogins) when ?summary=true
 * - Passes category, limit, offset query params
 */

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

const mockGetCurrentUser = vi.fn();
vi.mock('@/lib/auth-server', () => ({
  getCurrentUser: (...args: unknown[]) => mockGetCurrentUser(...args),
  getCurrentUserFromRequest: (...args: unknown[]) => mockGetCurrentUser(...args),
  requireAdmin: (...args: unknown[]) => mockGetCurrentUser(...args),
}));

const mockQueryAudit = vi.fn();
const mockGetAuditStats = vi.fn();
vi.mock('@/lib/platform-client', () => ({
  queryAudit: (...args: unknown[]) => mockQueryAudit(...args),
  getAuditStats: (...args: unknown[]) => mockGetAuditStats(...args),
}));

import { GET } from '@/app/api/audit/route';

async function callAudit(qs = '') {
  const { NextRequest } = await import('next/server');
  return GET(
    new NextRequest(
      new Request(`http://localhost:3001/api/audit${qs}`, {
        headers: { Authorization: 'Bearer test' },
      })
    )
  );
}

const admin = { id: 'usr_a', role: 'admin' };

describe('GET /api/audit', () => {
  beforeEach(() => vi.clearAllMocks());

  it('returns 401 when unauthenticated', async () => {
    mockGetCurrentUser.mockResolvedValue(null);
    const res = await callAudit();
    expect(res.status).toBe(401);
  });

  it('returns entries list with total by default', async () => {
    mockGetCurrentUser.mockResolvedValue(admin);
    mockQueryAudit.mockResolvedValue({
      records: [{ id: 'aud_1', category: 'auth', action: 'login_success' }],
      count: 1,
    });

    const res = await callAudit();
    expect(res.status).toBe(200);
    const data = await res.json();
    expect(data.entries).toHaveLength(1);
    expect(data.total).toBe(1);
  });

  it('returns summary when ?summary=true', async () => {
    mockGetCurrentUser.mockResolvedValue(admin);
    mockGetAuditStats.mockResolvedValue({
      stats: { login_success: 485, login_failed: 15 },
      days: 90,
    });

    const res = await callAudit('?summary=true');
    expect(res.status).toBe(200);
    const data = await res.json();
    expect(data.total).toBe(500);
    expect(data.failedLogins).toBe(15);
    // Should NOT call queryAudit in summary mode
    expect(mockQueryAudit).not.toHaveBeenCalled();
  });

  it('passes category filter from query params', async () => {
    mockGetCurrentUser.mockResolvedValue(admin);
    mockQueryAudit.mockResolvedValue({ records: [], count: 0 });

    await callAudit('?category=auth&limit=50&offset=10');
    expect(mockQueryAudit).toHaveBeenCalledWith({
      category: 'auth',
      limit: 50,
      offset: 10,
    });
  });

  it('uses default limit=100 and offset=0', async () => {
    mockGetCurrentUser.mockResolvedValue(admin);
    mockQueryAudit.mockResolvedValue({ records: [], count: 0 });

    await callAudit();
    expect(mockQueryAudit).toHaveBeenCalledWith({
      category: undefined,
      limit: 100,
      offset: 0,
    });
  });
});
