<script setup lang="ts">
const pushApi = usePushApi();
const { data: jobs, pending, refresh } = await useAsyncData("jobs", () => pushApi.request<Record<string, any>[]>("/admin/jobs"), {
  default: () => [],
  immediate: false,
});

onMounted(async () => {
  pushApi.hydrateToken();
  if (pushApi.token.value) await refresh();
});
</script>

<template>
  <AdminShell>
    <TokenGate>
      <div class="space-y-6">
        <div class="flex items-center justify-between">
          <div>
            <h2 class="text-2xl font-bold text-gray-950">Zustellungen</h2>
            <p class="text-sm text-gray-500">Letzte technische Push-Aufträge aller Instanzen.</p>
          </div>
          <UButton icon="i-lucide-refresh-cw" variant="soft" :loading="pending" @click="refresh()">Aktualisieren</UButton>
        </div>
        <UCard>
          <div class="overflow-x-auto">
            <table class="w-full text-left text-sm">
              <thead class="text-gray-500">
                <tr>
                  <th class="py-2">Job</th>
                  <th>Status</th>
                  <th>Angenommen</th>
                  <th>Gesendet</th>
                  <th>Fehler</th>
                  <th>Letzter Fehler</th>
                  <th>Erstellt</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="job in jobs" :key="job.id" class="border-t border-gray-100">
                  <td class="py-2 font-mono">{{ job.deliveryJobId }}</td>
                  <td>{{ job.status }}</td>
                  <td>{{ job.acceptedCount }}</td>
                  <td>{{ job.sentCount }}</td>
                  <td>{{ job.failedCount }}</td>
                  <td>{{ job.lastErrorCode || "-" }}</td>
                  <td>{{ new Date(job.createdAt).toLocaleString() }}</td>
                </tr>
              </tbody>
            </table>
          </div>
        </UCard>
      </div>
    </TokenGate>
  </AdminShell>
</template>
