<template>
  <div>
    <h1 class="font-display text-2xl font-bold text-white mb-6">Médias</h1>

    <AdminMediaUpload class="mb-6" @uploaded="refresh" />

    <AdminMediaBrowser
      v-if="files"
      :files="files"
      @delete="deleteFile"
    />
  </div>
</template>

<script setup lang="ts">
definePageMeta({
  layout: 'admin',
  middleware: 'admin',
})

const { data: files, refresh } = await useFetch('/api/admin/media')

async function deleteFile(path: string) {
  if (!confirm(`Supprimer ${path} ?`)) return

  // Remove leading slash for the API path
  const apiPath = path.startsWith('/') ? path.slice(1) : path

  await $fetch(`/api/admin/media/${apiPath}`, { method: 'DELETE' })
  await refresh()
}
</script>
