<script setup lang="ts">
import Button from '@/components/ui/button/Button.vue';
import { bustUserCache } from '@/api/member';
import type { UserCacheBustResult } from '@shared/types/member';
import { ref } from 'vue';

const loading = ref(false);
const result = ref<UserCacheBustResult | null>(null);
const error = ref<string | null>(null);

async function onBustUserCache() {
    loading.value = true;
    error.value = null;

    try {
        result.value = await bustUserCache();
    } catch (err) {
        result.value = null;
        error.value = err instanceof Error ? err.message : 'Failed to bust user cache';
    } finally {
        loading.value = false;
    }
}
</script>

<template>
    <div class="max-w-3xl mx-auto pt-10 px-4">
        <h1 class="scroll-m-20 text-2xl font-semibold tracking-tight">Developer Tools</h1>
        <p class="mt-2 text-sm text-muted-foreground">
            Use this page to recover from stale in-memory authentication data after manual database changes.
        </p>

        <div class="mt-6 rounded-lg border p-5 bg-card">
            <p class="font-medium">Server User Cache</p>
            <p class="text-sm text-muted-foreground mt-1">
                This clears the API server's cached user session data so the next request reloads from the database.
            </p>

            <div class="mt-4 flex items-center gap-3">
                <Button :disabled="loading" @click="onBustUserCache">
                    {{ loading ? 'Busting Cache...' : 'Bust User Cache' }}
                </Button>
            </div>

            <p v-if="result" class="mt-4 text-sm text-green-700">
                Cache busted successfully. Cleared {{ result.clearedEntries }} entr{{ result.clearedEntries === 1 ? 'y' : 'ies' }} at
                {{ new Date(result.bustedAt).toLocaleString() }}.
            </p>
            <p v-if="error" class="mt-4 text-sm text-red-700">{{ error }}</p>
        </div>
    </div>
</template>
