
<template>
    <form @submit.prevent="validate">
    <div class="flex items-center justify-between ">
        <h1 class="text-3xl font-bold uppercase">
            {{ route.params.id ? 'Modifier transporteur' : 'Ajout transporteur' }}
        </h1>

        <button
            type="submit"
            class="text-xl uppercase bg-primary-500 text-white h-[50px] w-[272px] justify-self-end"
        >Enregistrer
        </button>
    </div>

    <div class="grid grid-cols-2 items-start gap-y-8 gap-x-40 mb-16">
        <UiTextInput
            label = "nom du fournisseur"
            id="carrier-name"
            v-model="form.name"
        />

        <UiTextInput
                label = "code fournisseur"
                id="code-id"
                v-model="form.code"
        />
    </div>
    </form>

</template>

<script setup lang="ts">
import {createCarrier, getCarrier, updateCarrier} from "~/services/carrier";
import type {CarrierData, CarrierFormData} from "~/services/dto/carrier-data";
const router = useRouter()
const route = useRoute()
const idCarrier = Number(route.params.id)
const isLoading = ref(false)
const isHydrating = ref(false)

const form = reactive<CarrierFormData>({
    code:'',
    name:''
})

definePageMeta({
    layout: 'default'
})

const hydrateFromUser = (carrier: CarrierData | null) => {
    if (!carrier) {
        return
    }
    isHydrating.value = true
    form.name = carrier.name ?? ''
    form.code = carrier.code ?? ''
    isHydrating.value = false
}

watch(
    () => idCarrier,
    async (id) => {
        if (id === null) {
            return
        }
        isLoading.value = true
        try {
            const user = await getCarrier(id)
            hydrateFromUser(user)
        } finally {
            isLoading.value = false
        }
    },
    {immediate: true}
)
async function validate() {

    const normalizedCarrierCode = form.code.trim()
    const normalizedCarrierName = form.name.trim()

    const basePayload = {
        name: normalizedCarrierName,
        code: normalizedCarrierCode

    }

    if(idCarrier){
        await updateCarrier(idCarrier, basePayload)
        navigate()
        return
    }
    await createCarrier(basePayload)
    navigate()
}

function navigate(){
    router.push("/admin/carrier/carrier-list")
}
</script>
