<script setup>
import { onMounted, ref } from 'vue';
import { RouterLink, useRoute, useRouter } from 'vue-router';
import { api, useForm } from '@Services/Api';
import { viewTo, apiTo, transl } from './Module';

import IconButton from '@Holos/Button/Icon.vue'
import PageHeader from '@Holos/PageHeader.vue';
import Form       from './Form.vue'

/** Definiciones */
const vroute = useRoute();
const router = useRouter();

/** Propiedades */
const form = useForm({
    id: null,
    code: '',
    sku: '',
    name: '',
    description: '',
    attributes: {},
    is_active: true,
    warehouse_classification_ids: [],
    comercial_classification_ids: []
});

/** Métodos */
function submit() {
    form.put(apiTo('update', { product: form.id }), {
        onSuccess: () => {
            Notify.success(Lang('register.edit.onSuccess'));
            router.push(viewTo({ name: 'index' }));
        },
    });
}

/** Ciclos */
onMounted(() => {
    api.get(apiTo('show', { product: vroute.params.id }), {
        onSuccess: (r) => {
            const product = r.product || r.data?.product;
            
            // Extraer IDs de clasificaciones
            const warehouseIds = product.warehouse_classifications?.map(c => c.id) || [];
            const comercialIds = product.comercial_classifications?.map(c => c.id) || [];
            
            form.fill({
                id: product.id,
                code: product.code,
                sku: product.sku,
                name: product.name,
                description: product.description,
                attributes: product.attributes || {},
                is_active: product.is_active,
                warehouse_classification_ids: warehouseIds,
                comercial_classification_ids: comercialIds
            });
        }
    });
});
</script>

<template>
    <PageHeader :title="transl('edit.title')">
        <RouterLink :to="viewTo({ name: 'index' })">
            <IconButton
                class="text-white"
                icon="arrow_back"
                :title="$t('return')"
                filled
            />
        </RouterLink>
    </PageHeader>
    
    <Form
        action="update"
        :form="form"
        @submit="submit"
    />
</template>
