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

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

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

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

  it('proxies login to platform-service and returns data', async () => {
    mockFetch.mockResolvedValue(
      jsonResponse({ accessToken: 'tok', user: { id: 'u1', role: 'user' } })
    );

    const res = await callLogin({ email: 'user@test.com', password: 'pass' });
    expect(res.status).toBe(200);
    const data = await res.json();
    expect(data.accessToken).toBe('tok');
  });

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

    const res = await callLogin({ email: 'bad@test.com', password: 'wrong' });
    expect(res.status).toBe(401);
    const data = await res.json();
    expect(data.error).toBe('Invalid credentials');
  });

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

    const res = await callLogin({ email: 'user@test.com', password: 'pass' });
    expect(res.status).toBe(502);
    const data = await res.json();
    expect(data.error).toContain('unavailable');
  });

  it('sends request to correct platform API URL', async () => {
    mockFetch.mockResolvedValue(jsonResponse({ ok: true }));

    await callLogin({ email: 'a@b.com', password: 'pass' });

    expect(mockFetch).toHaveBeenCalledWith(
      expect.stringContaining('/api/auth/login'),
      expect.objectContaining({ method: 'POST' })
    );
  });
});
