import { describe, expect, it } from 'vitest'
import { z } from 'zod'
import { mapProblemToFormFailure, validateFormSubmission } from '../formValidation'

const schema = z.object({ name: z.string().min(1, '이름은 필수입니다.'), quantity: z.number().int().positive('수량은 양수여야 합니다.') })

describe('validateFormSubmission', () => {
  it('returns typed data for valid input', () => {
    expect(validateFormSubmission(schema, { name: 'item', quantity: 2 })).toEqual({ success: true, data: { name: 'item', quantity: 2 } })
  })

  it('maps field errors and summary for invalid input', () => {
    const result = validateFormSubmission(schema, { name: '', quantity: 0 })
    expect(result.success).toBe(false)
    if (!result.success) {
      expect(result.error.summary).toBe('입력값을 확인해 주세요.')
      expect(result.error.fields.name).toContain('이름은 필수입니다.')
      expect(result.error.fields.quantity).toContain('수량은 양수여야 합니다.')
    }
  })

  it('uses a form-level bucket for root validation errors', () => {
    const result = validateFormSubmission(z.string().min(3, '너무 짧습니다.'), 'x')
    expect(result.success).toBe(false)
    if (!result.success) expect(result.error.fields._form).toContain('너무 짧습니다.')
  })

  it('maps server ProblemDetails field errors without mutating the response', () => {
    const problem = { title: '검증 실패', detail: '입력값 오류', errors: { name: ['중복 이름'] } }
    const mapped = mapProblemToFormFailure(problem)
    expect(mapped).toEqual({ summary: '입력값 오류', fields: { name: ['중복 이름'] } })
    expect(mapped.fields.name).not.toBe(problem.errors.name)
  })
})
