/**
 * Tests for POST /api/auth/mfa/verify (tracker dashboard — proxy to platform-service).
 */

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

import { POST } from '@/app/api/auth/mfa/verify/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 callVerify(body: object) {
  return POST({ json: async () => body } as never);
}

describe('POST /api/auth/mfa/verify (tracker)', () => {
  beforeEach(() => mockFetch.mockReset());

  it('forwards a successful verification and returns tokens', async () => {
    mockFetch.mockResolvedValue(jsonResponse({ accessToken: 'tok', user: { id: 'u1' } }));

    const res = await callVerify({ challengeToken: 'chal', code: '123456', method: 'totp' });

    expect(res.status).toBe(200);
    const data = await res.json();
    expect(data.accessToken).toBe('tok');
    expect(mockFetch).toHaveBeenCalledWith(
      expect.stringContaining('/api/auth/mfa/verify'),
      expect.objectContaining({ method: 'POST' })
    );
  });

  it('forwards the platform-service error status and message', async () => {
    mockFetch.mockResolvedValue(jsonResponse({ error: 'Invalid code' }, 401));

    const res = await callVerify({ challengeToken: 'chal', code: '000000', method: 'totp' });

    expect(res.status).toBe(401);
    expect((await res.json()).error).toBe('Invalid code');
  });

  it('uses a default error message when platform-service omits one', async () => {
    mockFetch.mockResolvedValue(jsonResponse({}, 403));

    const res = await callVerify({ challengeToken: 'chal', code: '000000' });

    expect(res.status).toBe(403);
    expect((await res.json()).error).toBe('MFA verification failed');
  });

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

    const res = await callVerify({ challengeToken: 'chal', code: '123456' });

    expect(res.status).toBe(502);
    expect((await res.json()).error).toBe('Platform service unavailable');
  });
});
