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

vi.mock('$lib/server/db', () => ({
  getPool: vi.fn()
}));

import { getPool } from '$lib/server/db';
import { GET } from './+server';

describe('health endpoint', () => {
  beforeEach(() => {
    vi.mocked(getPool).mockReset();
  });

  it('reports a disabled database when no connection string is configured', async () => {
    vi.mocked(getPool).mockReturnValue(null);

    const response = await GET();
    const body = await response.json();

    expect(response.status).toBe(200);
    expect(body).toMatchObject({
      status: 'ok',
      database: 'disabled'
    });
  });

  it('reports an available database when the query succeeds', async () => {
    vi.mocked(getPool).mockReturnValue({
      query: vi.fn().mockResolvedValue({})
    } as never);

    const response = await GET();
    const body = await response.json();

    expect(response.status).toBe(200);
    expect(body).toMatchObject({
      status: 'ok',
      database: 'up'
    });
  });

  it('reports a degraded status when the database query fails', async () => {
    vi.mocked(getPool).mockReturnValue({
      query: vi.fn().mockRejectedValue(new Error('connection refused'))
    } as never);

    const response = await GET();
    const body = await response.json();

    expect(response.status).toBe(503);
    expect(body).toMatchObject({
      status: 'degraded',
      database: 'down'
    });
  });
});
