<template>
    <Address type="supplier" :address="address" @validate="validate"/>
</template>

<script setup lang="ts">
import type {AddressData, AddressPayload} from "~/services/address";
import {createAddress, getAddress, updateAddress} from "~/services/address";
import {getSupplier, updateSupplier} from "~/services/supplier";
import type {SupplierData} from "~/services/dto/supplier-data";

definePageMeta({ layout: "default" })

const route = useRoute()
const router = useRouter()
const supplierId = computed(() => { return Number(route.query.supplierId) })
const supplier = ref<SupplierData|null>(null);
const addressId = computed(() => { return route.query.addressId !== undefined ? Number(route.query.addressId) : null })
const address = ref<AddressData|null>(null)

const validate = async (address: AddressPayload) => {
    try {
        if (addressId.value !== null) {
            await updateAddress(addressId.value, address)
        } else {
            await addAddress(address)
        }
    } finally {
        await router.push('/admin/supplier/' + supplierId.value)
    }
}

const addAddress = async (address: AddressPayload) => {
    const response: AddressData = await createAddress(address)
    const addressIRI = `/api/addresses/${response.id}`
    const existingIris = (supplier.value.addresses ?? []).map((item: any) => `/api/addresses/${item.id}`)
    const next = [...new Set([...existingIris, addressIRI])]

    return await updateSupplier(supplierId.value, { addresses: next })
}

onMounted(async () => {
    supplier.value = await getSupplier(supplierId.value)
    if (addressId.value !== null) {
        address.value = await getAddress(addressId.value)
    }
})
</script>
