/**
 * Tests for GET /api/auth/me (tracker dashboard — proxy to platform-service)
 */

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

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

const mockFetch = vi.fn();
vi.stubGlobal('fetch', mockFetch);

function jsonResponse(data: unknown, status = 200) {
  return {
    ok: status >= 200 && status < 300,
    status,
    json: () => Promise.resolve(data),
  } as unknown as Response;
}

function callMe(auth?: string) {
  const headerMap = new Map<string, string>();
  if (auth) {
    headerMap.set('authorization', auth);
  }

  return GET({
    headers: {
      get: (key: string) => headerMap.get(key.toLowerCase()) ?? null,
    },
  } as never);
}

describe('GET /api/auth/me (tracker)', () => {
  beforeEach(() => mockFetch.mockReset());

  it('proxies to platform-service and returns user data', async () => {
    mockFetch.mockResolvedValue(
      jsonResponse({ user: { id: 'u1', email: 'a@b.com', role: 'user' } })
    );

    const res = await callMe('Bearer valid-token');
    expect(res.status).toBe(200);
    const data = await res.json();
    expect(data.user.id).toBe('u1');
  });

  it('forwards authorization header', async () => {
    mockFetch.mockResolvedValue(jsonResponse({ user: { id: 'u1' } }));

    await callMe('Bearer my-jwt');
    expect(mockFetch).toHaveBeenCalledWith(
      expect.stringContaining('/api/auth/me'),
      expect.objectContaining({
        headers: expect.objectContaining({ Authorization: 'Bearer my-jwt' }),
      })
    );
  });

  it('returns error status from platform-service', async () => {
    mockFetch.mockResolvedValue(jsonResponse({ error: 'Unauthorized' }, 401));

    const res = await callMe('Bearer expired');
    expect(res.status).toBe(401);
  });

  it('returns 502 when platform-service reports unavailability', async () => {
    mockFetch.mockResolvedValue(jsonResponse({ error: 'Platform service unavailable' }, 502));

    const res = await callMe('Bearer tok');
    expect(res.status).toBe(502);
    const data = await res.json();
    expect(data.error).toContain('unavailable');
  });

  it('sends empty auth when no header provided', async () => {
    mockFetch.mockResolvedValue(jsonResponse({ error: 'Unauthorized' }, 401));

    await callMe();
    expect(mockFetch).toHaveBeenCalledWith(
      expect.any(String),
      expect.objectContaining({
        headers: expect.objectContaining({ Authorization: '' }),
      })
    );
  });
});
