<template>
  <v-menu>
    <template #activator="{ props }">
      <v-btn v-bind="props" variant="outlined" prepend-icon="mdi-wrench" append-icon="mdi-chevron-down">
        Maintenance
      </v-btn>
    </template>
    <v-list density="compact">
      <v-list-item
        prepend-icon="mdi-refresh"
        title="Retry failed"
        subtitle="Re-enqueue every failed import task"
        @click="onRetry"
      />
      <v-list-item
        prepend-icon="mdi-broom"
        title="Clear stuck"
        subtitle="Mark long-running import tasks failed and finalize their batch"
        @click="onClear"
      />
      <v-list-item
        :disabled="true"
        prepend-icon="mdi-download-box"
        title="Export failed logs"
        subtitle="CSV dump — v2"
      >
        <v-tooltip activator="parent" location="start">Deferred to a future release</v-tooltip>
      </v-list-item>
    </v-list>
  </v-menu>
</template>

<script setup>
import { toast } from '../../utils/toast.js'
import { useImportStore } from '../../stores/import.js'

const emit = defineEmits(['refresh'])
const importStore = useImportStore()

async function onRetry() {
  try {
    await importStore.retryFailed()
    toast({ text: 'Retry queued', type: 'success' })
    emit('refresh')
  } catch (e) {
    toast({ text: `Retry failed: ${e?.detail || e?.message || e}`, type: 'error' })
  }
}

async function onClear() {
  try {
    const body = await importStore.clearStuck()
    const n = body?.cleared ?? 0
    toast({
      text: n ? `Cleared ${n} stuck task${n === 1 ? '' : 's'}` : 'Nothing stuck',
      type: 'success',
    })
    emit('refresh')
  } catch (e) {
    toast({ text: `Clear failed: ${e?.detail || e?.message || e}`, type: 'error' })
  }
}
</script>
