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

<script setup lang="ts">
useHead({ title: 'Adresse client' })

import type { AddressData, AddressPayload } from "~/services/address"
import { createAddress, getAddress, updateAddress } from "~/services/address"
import { getCustomer, updateCustomer } from "~/services/customer"
import type { CustomerData } from "~/services/dto/customer-data"

const route = useRoute()
const router = useRouter()
const customerId = computed(() => Number(route.query.customerId))
const customer = ref<CustomerData | null>(null)
const addressId = computed(() => (route.query.addressId !== undefined ? Number(route.query.addressId) : null))
const address = ref<AddressData | null>(null)

const validate = async (payload: AddressPayload) => {
    if (addressId.value !== null) {
        await updateAddress(addressId.value, payload)
    } else {
        await addAddress(payload)
        await router.push("/admin/customer/" + customerId.value)
    }
}

const addAddress = async (payload: AddressPayload) => {
    const response: AddressData = await createAddress(payload)
    const addressIRI = `/api/addresses/${response.id}`
    const existingIris = (customer.value?.addresses ?? [])
        .map((item: any) => (typeof item === "string" ? item : `/api/addresses/${item.id}`))
        .filter((iri: string | null) => Boolean(iri)) as string[]
    const next = [...new Set([...existingIris, addressIRI])]

    return await updateCustomer(customerId.value, { addresses: next })
}

onMounted(async () => {
    customer.value = await getCustomer(customerId.value)
    if (addressId.value !== null) {
        address.value = await getAddress(addressId.value)
    }
})
</script>
