<script setup lang="ts">
definePageMeta({
    rights: ['admin'],
})
const job = ref<string>('');

const toaster = useToast();
const data = ref(), status = ref<'idle' | 'pending' | 'success' | 'error'>('idle'), success = ref(false), err = ref(false), error = ref();
async function fetch()
{
    status.value = 'pending';
    data.value = null;
    error.value = null;
    err.value = false;
    success.value = false;

    try
    {
        data.value = await $fetch(`/api/admin/jobs/${job.value}`, {
            method: 'POST',
        });
        status.value = 'success';
        error.value = null;
        err.value = false;
        success.value = true;

        toaster.add({ duration: 10000, content: data.value ?? 'Job executé avec succès', type: 'success', timer: true, });
    }
    catch(e)
    {
        status.value = 'error';
        error.value = e;
        err.value = true;
        success.value = false;

        toaster.add({ duration: 10000, content: error.value, type: 'error', timer: true, });
    }
}
</script>

<template>
    <Head>
        <Title>Administration</Title>
    </Head>
    <div class="flex flex-col justify-start">
        <ProseH2>Administration</ProseH2>
        <Select label="Job" v-model="job">
            <SelectItem label="Synchroniser" value="sync" />
            <SelectItem label="Nettoyer la base" value="clear" disabled />
            <SelectItem label="Reconstruire" value="rebuild" disabled />
        </Select>
        <Button class="self-center" @click="() => !!job && fetch()" :loading="status === 'pending'">
            <span>Executer</span>
        </Button>
    </div>
</template>