<template>
    <div>
        <h1 class="text-3xl mb-8">Debug</h1>
        <div class="stats shadow mb-8">
            <div class="stat">
                <div class="stat-title">DB Ping Status</div>
                <div class="stat-value">{{ data?.db_ping_status || "?" }}</div>
            </div>
            <div class="stat">
                <div class="stat-title">Entries Count</div>
                <div class="stat-value">{{ data?.entries.length || "?" }}</div>
                <div class="stat-actions">
                    <button class="btn btn-sm" @click="addRandomEntry">Add entry</button>
                </div>
            </div>
            <div class="stat">
                <div class="stat-title">Network status</div>
                <div class="stat-value">{{ status }}</div>
                <div class="stat-description">{{ error }}</div>
            </div>
        </div>
        <div>
            <h2 class="text-2xl mb-4">Entries</h2>
            <table class="table">
                <thead>
                    <tr>
                        <th>Id</th>
                        <th>Title</th>
                        <th>Text</th>
                    </tr>
                </thead>
                <tbody>
                    <tr v-for="entry in data?.entries" :key="entry.id">
                        <td>{{ entry.id }}</td>
                        <td>{{ entry.title }}</td>
                        <td>{{ entry.text }}</td>
                    </tr>
                </tbody>
            </table>
        </div>
    </div>
</template>

<script setup lang="ts">
    type Entry = {
        id: number;
        title: string;
        text: string;
    };
    type DebugResponse = {
        db_ping_status: string;
        entries: Entry[];
    };

    
    // TODO : handle a default backend URL by building a custom `$fetch` and `useFetch` functions with a `baseURL` option : https://nuxt.com/docs/guide/recipes/custom-usefetch#custom-fetch
    
    const { data, refresh, error, status } = await useFetch<DebugResponse>('http://127.0.0.1:8080/debug');

    async function addRandomEntry() {
        await $fetch('http://127.0.0.1:8080/debug/add_random', {
            method: 'POST',
        });
        refresh();
    }

</script>
