<template>
    <form @submit.prevent="validate">

        <div class="grid grid-cols-2 gap-x-40 gap-y-8 mb-16">
            <UiNumberInput
                label="Pesée à vide"
                v-model="form.weights[0].weight"
                :disabled="!auth.isAdmin"
                :min="0"
            />

            <UiNumberInput
                label="Pesée à plein"
                v-model="form.weights[1].weight"
                :disabled="!auth.isAdmin"
                :min="0"
            />
        </div>

        <div class="flex justify-center">
            <button
                type="submit"
                class="text-xl uppercase bg-primary-500 text-white h-[50px] w-[272px]"
                :disabled="!auth.isAdmin"
            >
                Valider
            </button>
        </div>

    </form>
</template>

<script setup lang="ts">
import type {ReceptionFormWeight} from '~/services/dto/reception-data'
import { getReception } from '~/services/reception'
import {updateWeight} from "~/services/weight";
import {useAuthStore} from "~/stores/auth";

const props = defineProps<{
    idReception: number
}>()

const idReception = props.idReception
const auth = useAuthStore()

const form = reactive({
    weights: [
        { id: 0, type: 'tare' as const, weight: 0 },
        { id: 0, type: 'gross' as const, weight: 0 }
    ]
})

const hydrateFromReception = (reception: ReceptionFormWeight) => {
    const tare = reception.weights.find(weight => weight.type === 'tare')
    const gross = reception.weights.find(weight => weight.type === 'gross')

    if (tare) form.weights[0] = { ...tare }
    if (gross) form.weights[1] = { ...gross }
}

onMounted(async () => {
    const reception = await getReception(idReception)
    hydrateFromReception(reception)
})

async function validate() {

    for (const weight of form.weights) {
        if (weight.id) {
            await updateWeight(weight.id, {weight: weight.weight})
        }
    }
}
</script>
