import { describe, it, expect, afterEach } from 'vitest';
import { buildServer } from './server.js';

describe('buildServer', () => {
  let app: Awaited<ReturnType<typeof buildServer>> | null = null;

  afterEach(async () => {
    if (app) {
      await app.close();
      app = null;
    }
  });

  it('should create a Fastify instance', async () => {
    app = await buildServer();
    expect(app).toBeDefined();
  });

  it('should respond to /health with status ok', async () => {
    app = await buildServer();
    const response = await app.inject({ method: 'GET', url: '/health' });
    expect(response.statusCode).toBe(200);
    const body = JSON.parse(response.body);
    expect(body.status).toBe('ok');
    expect(body.timestamp).toBeDefined();
  });

  it('should return 403 for non-localhost requests', async () => {
    app = await buildServer();
    const response = await app.inject({
      method: 'GET',
      url: '/health',
      headers: { host: 'example.com:3001' },
    });
    expect(response.statusCode).toBe(403);
    const body = JSON.parse(response.body);
    expect(body.error).toBe('Access restricted to localhost');
  });

  it('should allow localhost requests', async () => {
    app = await buildServer();
    const response = await app.inject({
      method: 'GET',
      url: '/health',
      headers: { host: 'localhost:3001' },
    });
    expect(response.statusCode).toBe(200);
  });

  it('should allow 127.0.0.1 requests', async () => {
    app = await buildServer();
    const response = await app.inject({
      method: 'GET',
      url: '/health',
      headers: { host: '127.0.0.1:3001' },
    });
    expect(response.statusCode).toBe(200);
  });

  it('should handle errors with structured response', async () => {
    app = await buildServer();
    // Register a route that throws
    app.get('/test-error', async () => {
      throw new Error('Test error');
    });
    const response = await app.inject({ method: 'GET', url: '/test-error' });
    expect(response.statusCode).toBe(500);
    const body = JSON.parse(response.body);
    expect(body.error).toBe('Internal Server Error');
    expect(body.statusCode).toBe(500);
  });
});
