import { describe, it, expect } from 'vitest'
import { mapViolationsToRecord } from '../api'

/**
 * Tests de `mapViolationsToRecord` — fondation du mapping erreur→champ des
 * formulaires (ERP-101). Transforme un payload 422 API Platform en
 * `Record<propertyPath, message>` directement consommable par la prop `:error`
 * des composants `Malio*`.
 */
describe('mapViolationsToRecord', () => {
    it('mappe chaque violation par son propertyPath (format `violations`)', () => {
        const data = {
            violations: [
                { propertyPath: 'companyName', message: 'Obligatoire.' },
                { propertyPath: 'siren', message: 'SIREN deja utilise.' },
            ],
        }
        expect(mapViolationsToRecord(data)).toEqual({
            companyName: 'Obligatoire.',
            siren: 'SIREN deja utilise.',
        })
    })

    it('supporte le format negocie `hydra:violations`', () => {
        const data = {
            'hydra:violations': [
                { propertyPath: 'email', message: 'Adresse invalide.' },
            ],
        }
        expect(mapViolationsToRecord(data)).toEqual({ email: 'Adresse invalide.' })
    })

    it('renvoie un objet vide quand il n\'y a pas de violation exploitable', () => {
        expect(mapViolationsToRecord({})).toEqual({})
        expect(mapViolationsToRecord(null)).toEqual({})
        expect(mapViolationsToRecord({ violations: [] })).toEqual({})
    })

    it('ignore les violations sans propertyPath', () => {
        const data = {
            violations: [
                { propertyPath: '', message: 'Erreur globale.' },
                { propertyPath: 'iban', message: 'IBAN invalide.' },
            ],
        }
        expect(mapViolationsToRecord(data)).toEqual({ iban: 'IBAN invalide.' })
    })

    it('en cas de doublon de propertyPath, la derniere violation gagne', () => {
        const data = {
            violations: [
                { propertyPath: 'name', message: 'Premier message.' },
                { propertyPath: 'name', message: 'Second message.' },
            ],
        }
        expect(mapViolationsToRecord(data)).toEqual({ name: 'Second message.' })
    })
})
