import { describe, it, expect } from 'vitest';
import { defineForm } from '@platform-modules/forms';
import { CONTACT_FORM, CONTACT_FORM_DEF, mapFormError } from './forms.js';

describe('CONTACT_FORM', () => {
  it('defineForm returns ok for the contact definition', () => {
    const result = defineForm(CONTACT_FORM_DEF);
    expect(result.ok).toBe(true);
    if (result.ok) {
      expect(result.value.id).toBe('contact');
      expect(result.value.fields).toHaveLength(3);
    }
  });

  it('CONTACT_FORM is the validated export', () => {
    expect(CONTACT_FORM.id).toBe('contact');
    expect(CONTACT_FORM.antispam?.honeypot).toBe('website');
    expect(CONTACT_FORM.antispam?.minFillMs).toBe(2000);
  });
});

describe('mapFormError', () => {
  it('maps FieldError[] to 422 with errors body', async () => {
    const res = mapFormError([
      { field: 'email', code: 'required', message: 'Email is required.' },
    ]);
    expect(res.status).toBe(422);
    const body = await res.json();
    expect(body.errors).toEqual([
      { field: 'email', code: 'required', message: 'Email is required.' },
    ]);
  });

  it('maps antispam too-fast to 422', async () => {
    const res = mapFormError({ reason: 'too-fast' });
    expect(res.status).toBe(422);
    const body = await res.json();
    expect(body.error.code).toBe('validation_error');
  });

  it('maps antispam bad-token to 422', async () => {
    const res = mapFormError({ reason: 'bad-token' });
    expect(res.status).toBe(422);
  });

  it('maps honeypot to 200 no-op', async () => {
    const res = mapFormError({ reason: 'honeypot' });
    expect(res.status).toBe(200);
  });

  it('maps unknown to 500', async () => {
    const res = mapFormError(new Error('boom'));
    expect(res.status).toBe(500);
    const body = await res.json();
    expect(body.error.code).toBe('internal_error');
  });
});
