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

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

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

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

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

  it('returns ok when all required env vars are set', async () => {
    process.env.PLATFORM_API_URL = 'http://localhost:4003';
    process.env.JWT_SECRET = 'test-secret';
    process.env.DEFAULT_PRODUCT_ID = 'test-product';

    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).toBeDefined();
    expect(data.checks).toBeInstanceOf(Array);
  });

  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.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/);
  });
});
