<template>
  <!-- #859: delete ImageRecords whose backing file is gone from disk (orphans
       left by the external-attach unlink bug) so they stop 404-ing on playback. -->
  <MaintenanceTile
    icon="mdi-file-remove-outline"
    title="Repair missing files"
    blurb="Remove records whose file is gone from disk."
    :open="busy"
  >
      <p class="text-body-2 mb-3">
        Scans every image/video record and removes any whose underlying file is
        gone from disk — orphaned records that otherwise 404 when you open the
        post. Safe: it <strong>aborts without deleting</strong> if a large share of
        files look missing (which means a storage/NFS hiccup, not real orphans).
        Run it only when storage is healthy.
      </p>
      <v-btn color="primary" rounded="pill" :loading="busy" @click="run">
        <v-icon start>mdi-file-remove-outline</v-icon> Repair missing-file records
      </v-btn>
      <span v-if="queued" class="ml-3 text-caption text-success">Queued ✓</span>
      <QueueStatusBar queue="maintenance" queue-label="Maintenance" />
  </MaintenanceTile>
</template>

<script setup>
import { ref } from 'vue'

import { useApi } from '../../composables/useApi.js'
import { toast } from '../../utils/toast.js'
import MaintenanceTile from '../common/MaintenanceTile.vue'
import QueueStatusBar from './QueueStatusBar.vue'

const api = useApi()
const busy = ref(false)
const queued = ref(false)

async function run () {
  busy.value = true
  queued.value = false
  try {
    await api.post('/api/admin/maintenance/prune-missing-files')
    queued.value = true
    toast({ text: 'Missing-file repair queued', type: 'success' })
  } catch (e) {
    toast({ text: e?.body?.detail || e?.message || 'Failed to queue', type: 'error' })
  } finally {
    busy.value = false
  }
}
</script>
