/**
 * Tests for GET /api/auth/me
 *
 * Covers:
 * - 401 when no auth header
 * - 401 when invalid token
 * - 200 with user profile (excludes passwordHash)
 */

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

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

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

async function callMe(token?: string) {
  const { NextRequest } = await import('next/server');
  const headers: Record<string, string> = {};
  if (token) headers['Authorization'] = token;
  return GET(new NextRequest(new Request('http://localhost:3001/api/auth/me', { headers })));
}

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

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

  it('returns 401 with no auth header', async () => {
    const res = await callMe();
    expect(res.status).toBe(401);
  });

  it('returns 401 with invalid token', async () => {
    mockGetMeViaService.mockRejectedValue(new Error('Unauthorized'));
    const res = await callMe('Bearer invalid_token');
    expect(res.status).toBe(401);
  });

  it('returns user profile on valid token', async () => {
    mockGetMeViaService.mockResolvedValue(serviceUser);
    const res = await callMe('Bearer valid_token');
    expect(res.status).toBe(200);
    const data = await res.json();
    expect(data.id).toBe('usr_admin_1');
    expect(data.email).toBe('admin@example.com');
    expect(data.role).toBe('super_admin');
    // passwordHash must NOT be returned
    expect(data.passwordHash).toBeUndefined();
  });
});
