/**
 * Tests for GET /api/referrals (admin view).
 *
 * Covers:
 * - 401 when not authenticated
 * - 200 returns referrals + stats
 * - 200 summary mode returns stats only
 * - 500 on unexpected error
 */

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

// ── Mocks ──────────────────────────────────────────────────────────────

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 mockListReferrals = vi.fn();
const mockGetReferralStats = vi.fn();
vi.mock('@/lib/growth-client', () => ({
  listReferrals: (...args: unknown[]) => mockListReferrals(...args),
  getReferralStats: (...args: unknown[]) => mockGetReferralStats(...args),
}));

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

// ── Helpers ────────────────────────────────────────────────────────────

const adminUser = {
  id: 'usr_admin_1',
  email: 'admin@example.com',
  name: 'Admin',
  role: 'super_admin',
  plan: 'enterprise',
};

async function callGET(params = '', token = 'Bearer admin_tok') {
  const { NextRequest } = await import('next/server');
  return GET(
    new NextRequest(
      new Request(`http://localhost:3001/api/referrals${params}`, {
        headers: { Authorization: token },
      })
    )
  );
}

// ── Tests ──────────────────────────────────────────────────────────────

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

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

  it('returns referrals and stats', async () => {
    mockGetCurrentUser.mockResolvedValue(adminUser);
    mockListReferrals.mockResolvedValue({
      referrals: [{ id: 'ref_1', referrerEmail: 'a@b.com', status: 'signed_up' }],
    });
    mockGetReferralStats.mockResolvedValue({ total: 5, completed: 3, rewarded: 1 });

    const res = await callGET();
    expect(res.status).toBe(200);
    const data = await res.json();
    expect(data.referrals).toHaveLength(1);
    expect(data.stats.total).toBe(5);
    expect(data.stats.completed).toBe(3);
    expect(data.stats.rewarded).toBe(1);
  });

  it('returns summary only when mode=summary', async () => {
    mockGetCurrentUser.mockResolvedValue(adminUser);
    mockGetReferralStats.mockResolvedValue({ total: 10, completed: 6, rewarded: 2 });

    const res = await callGET('?mode=summary');
    expect(res.status).toBe(200);
    const data = await res.json();
    expect(data.total).toBe(10);
    expect(data.completed).toBe(6);
    expect(data.referrals).toBeUndefined();
  });

  it('returns 500 on unexpected error', async () => {
    mockGetCurrentUser.mockRejectedValue(new Error('DB down'));
    const res = await callGET();
    expect(res.status).toBe(500);
  });
});
