/**
 * Tests for GET /api/health (tracker dashboard)
 */

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

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

describe('GET /api/health', () => {
  const originalEnv = { ...process.env };

  afterEach(() => {
    process.env = { ...originalEnv };
    vi.unstubAllGlobals();
  });

  it('returns ok when all required env vars are set and platform-service is healthy', async () => {
    process.env.PLATFORM_API_URL = 'http://localhost:4003';
    process.env.JWT_SECRET = 'test-secret';
    process.env.DEFAULT_PRODUCT_ID = 'test-product';
    vi.stubGlobal(
      'fetch',
      vi.fn(async () => new Response(JSON.stringify({ status: 'ok' }), { status: 200 }))
    );

    const res = await GET();
    expect(res.status).toBe(200);
    const data = await res.json();
    expect(data.status).toBe('ok');
    expect(data.service).toBe('tracker-dashboard');
    expect(data.timestamp).toMatch(/^\d{4}-\d{2}-\d{2}T/);
    expect(data.checks).toEqual([
      {
        name: 'env',
        status: 'pass',
        message: '3 required vars set',
      },
      {
        name: 'platform-service',
        status: 'pass',
        message: 'healthy',
      },
    ]);
    expect(fetch).toHaveBeenCalledWith('http://localhost:4003/health', expect.any(Object));
  });

  it('returns degraded when platform-service health check fails', async () => {
    process.env.PLATFORM_API_URL = 'http://localhost:4003';
    process.env.JWT_SECRET = 'test-secret';
    process.env.DEFAULT_PRODUCT_ID = 'test-product';
    vi.stubGlobal(
      'fetch',
      vi.fn(async () => new Response(JSON.stringify({ status: 'degraded' }), { status: 503 }))
    );

    const res = await GET();
    expect(res.status).toBe(503);
    const data = await res.json();
    expect(data.status).toBe('degraded');
    expect(data.checks).toContainEqual({
      name: 'platform-service',
      status: 'fail',
      message: 'HTTP 503',
    });
  });

  it('returns degraded when platform-service health check throws', async () => {
    process.env.PLATFORM_API_URL = 'http://localhost:4003';
    process.env.JWT_SECRET = 'test-secret';
    process.env.DEFAULT_PRODUCT_ID = 'test-product';
    vi.stubGlobal(
      'fetch',
      vi.fn(async () => {
        throw new Error('connection refused');
      })
    );

    const res = await GET();
    expect(res.status).toBe(503);
    const data = await res.json();
    expect(data.status).toBe('degraded');
    expect(data.checks).toContainEqual({
      name: 'platform-service',
      status: 'fail',
      message: 'connection refused',
    });
  });

  it('returns a generic degraded message for non-Error platform failures', async () => {
    process.env.PLATFORM_API_URL = 'http://localhost:4003';
    process.env.JWT_SECRET = 'test-secret';
    process.env.DEFAULT_PRODUCT_ID = 'test-product';
    vi.stubGlobal(
      'fetch',
      vi.fn(async () => {
        throw 'boom';
      })
    );

    const res = await GET();
    expect(res.status).toBe(503);
    const data = await res.json();
    expect(data.checks).toContainEqual({
      name: 'platform-service',
      status: 'fail',
      message: 'health check failed',
    });
  });

  it('returns degraded when env vars are missing', async () => {
    delete process.env.PLATFORM_API_URL;
    delete process.env.JWT_SECRET;
    delete process.env.DEFAULT_PRODUCT_ID;

    const res = await GET();
    expect(res.status).toBe(503);
    const data = await res.json();
    expect(data.status).toBe('degraded');
    expect(data.service).toBe('tracker-dashboard');
    expect(data.checks[0].status).toBe('fail');
    expect(data.checks[0].message).toContain('Missing');
  });

  it('includes timestamp in ISO format', async () => {
    process.env.PLATFORM_API_URL = 'http://localhost:4003';
    process.env.JWT_SECRET = 'secret';
    process.env.DEFAULT_PRODUCT_ID = 'test-product';

    const res = await GET();
    const data = await res.json();
    expect(data.timestamp).toMatch(/^\d{4}-\d{2}-\d{2}T/);
  });
});
