import { describe, it, expect, vi } from 'vitest'
import { mount } from '@vue/test-utils'
import { defineComponent, h, ref, computed } from 'vue'
import { emptyProviderContact } from '~/modules/technique/types/providerForm'
import ProviderContactBlock from '../ProviderContactBlock.vue'

// Auto-imports Nuxt/Vue utilises sans import explicite par le composant.
vi.stubGlobal('useI18n', () => ({ t: (key: string) => key }))
vi.stubGlobal('ref', ref)
vi.stubGlobal('computed', computed)

/** Stub d'un champ Malio qui re-expose la prop `error` recue dans un data-* attribut. */
function errorProbe(testid: string) {
    return defineComponent({
        name: `Probe-${testid}`,
        props: {
            modelValue: { type: [String, Number, null], default: undefined },
            error: { type: String, default: '' },
            label: { type: String, default: '' },
            readonly: { type: Boolean, default: false },
        },
        setup(props) {
            return () => h('div', { 'data-testid': testid, 'data-error': props.error })
        },
    })
}

function mountBlock(errors?: Record<string, string>) {
    return mount(ProviderContactBlock, {
        props: {
            modelValue: emptyProviderContact(),
            ...(errors ? { errors } : {}),
        },
        global: {
            stubs: {
                MalioButtonIcon: true,
                MalioInputPhone: true,
                MalioInputText: errorProbe('contact-text'),
                MalioInputEmail: errorProbe('contact-email'),
            },
        },
    })
}

describe('ProviderContactBlock — mapping erreur par champ (ERP-101)', () => {
    it('affiche l\'erreur serveur sur le champ email via la prop errors', () => {
        const wrapper = mountBlock({ email: 'L\'adresse email n\'est pas valide.' })
        expect(wrapper.find('[data-testid="contact-email"]').attributes('data-error')).toBe('L\'adresse email n\'est pas valide.')
    })

    it('laisse les champs sans erreur quand errors est absent', () => {
        const wrapper = mountBlock()
        expect(wrapper.find('[data-testid="contact-email"]').attributes('data-error')).toBe('')
    })
})
