import { describe, expect, it } from 'vitest';
import { z } from 'zod';
import { parseJson } from '../http-input.js';
import { AppError } from '../errors.js';

const schema = z.object({ name: z.string().min(1), age: z.number().int().nonnegative() });

describe('parseJson', () => {
  it('returns the parsed value for valid input', () => {
    expect(parseJson(schema, { name: 'ana', age: 3 })).toEqual({ name: 'ana', age: 3 });
  });

  it('throws AppError 400 VALIDATION_ERROR with field issues for invalid input', () => {
    let caught: unknown;
    try {
      parseJson(schema, { name: '', age: -1 });
    } catch (error) {
      caught = error;
    }
    expect(caught).toBeInstanceOf(AppError);
    const appError = caught as AppError;
    expect(appError.statusCode).toBe(400);
    expect(appError.code).toBe('VALIDATION_ERROR');
    expect(appError.details).toEqual([
      { path: 'name', message: expect.any(String) },
      { path: 'age', message: expect.any(String) },
    ]);
  });

  it('rejects non-object input when the schema expects an object', () => {
    expect(() => parseJson(schema, 'not-an-object')).toThrowError(AppError);
  });
});
