/**
 * Tests for POST /api/telemetry/ingest (tracker dashboard — proxy to platform-service).
 */

import { describe, it, expect, vi, beforeEach } from 'vitest';
import type { NextRequest } from 'next/server';

import { POST } from '@/app/api/telemetry/ingest/route';

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

function mockRequest(body: string): NextRequest {
  return { text: async () => body } as unknown as NextRequest;
}

describe('POST /api/telemetry/ingest (tracker)', () => {
  beforeEach(() => mockFetch.mockReset());

  it('forwards the raw beacon body to the telemetry events endpoint', async () => {
    mockFetch.mockResolvedValue({ ok: true, status: 200 } as Response);

    const payload = JSON.stringify({ events: [{ eventName: 'page_view' }] });
    const res = await POST(mockRequest(payload));

    expect(res.status).toBe(200);
    expect((await res.json()).ok).toBe(true);
    expect(mockFetch).toHaveBeenCalledWith(
      expect.stringContaining('/api/telemetry/events'),
      expect.objectContaining({
        method: 'POST',
        body: payload,
        headers: expect.objectContaining({ 'Content-Type': 'application/json' }),
      })
    );
  });

  it('mirrors a non-ok platform-service status', async () => {
    mockFetch.mockResolvedValue({ ok: false, status: 429 } as Response);

    const res = await POST(mockRequest('{}'));

    expect(res.status).toBe(429);
    expect((await res.json()).ok).toBe(false);
  });

  it('returns 502 when the platform-service is unreachable', async () => {
    mockFetch.mockImplementationOnce(() => Promise.reject(new Error('ECONNREFUSED')));

    const res = await POST(mockRequest('{}'));

    expect(res.status).toBe(502);
    expect((await res.json()).ok).toBe(false);
  });
});
