<template>
  <!-- Éditeur des délais SLA (réponse / résolution) PAR FILE (type de ticket) + PRIORITÉ. Stocké dans le hub, appliqué aux pastilles SLA. -->
  <div class="ops-card q-mb-md">
    <q-expansion-item header-class="section-header" expand-icon-class="text-grey-7">
      <template #header>
        <q-item-section avatar><q-icon name="timer" color="primary" size="24px" /></q-item-section>
        <q-item-section>
          <div class="text-subtitle1 text-weight-bold">Délais SLA — réponse / résolution</div>
          <div class="text-caption text-grey-6">Cibles par file (type de ticket) + priorité. « Défaut » s'applique aux types sans politique propre.</div>
        </q-item-section>
      </template>
      <q-card><q-card-section>
        <div class="row items-center q-gutter-sm q-mb-md">
          <q-select dense outlined v-model="file" :options="fileOptions" label="File (type de ticket)" emit-value map-options style="min-width:260px" @update:model-value="loadFile" />
          <q-space />
          <q-btn unelevated no-caps color="primary" icon="save" label="Enregistrer" :loading="saving" @click="save" />
        </div>
        <q-markup-table flat bordered dense>
          <thead><tr><th class="text-left">Priorité</th><th>Réponse (h)</th><th>Résolution (h)</th></tr></thead>
          <tbody>
            <tr v-for="pr in PRIORITIES" :key="pr">
              <td class="text-left"><span class="ops-badge" :class="priorityClass(pr)">{{ pr }}</span></td>
              <td class="text-center"><q-input dense outlined type="number" min="0" step="0.25" v-model.number="edit[pr].response" input-class="text-center" style="width:96px;margin:0 auto" /></td>
              <td class="text-center"><q-input dense outlined type="number" min="0" step="0.25" v-model.number="edit[pr].resolution" input-class="text-center" style="width:96px;margin:0 auto" /></td>
            </tr>
          </tbody>
        </q-markup-table>
        <div class="text-caption text-grey-6 q-mt-sm">Valeurs en heures (0.25 = 15 min). Appliquées immédiatement aux pastilles SLA des tickets.</div>
      </q-card-section></q-card>
    </q-expansion-item>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useQuasar } from 'quasar'
import { listDocs } from 'src/api/erp'
import { useSla } from 'src/composables/useSla'
import { priorityClass } from 'src/composables/useStatusClasses'

const $q = useQuasar()
const { policies, defaults, loadPolicies, savePolicies } = useSla()
const PRIORITIES = ['Urgent', 'High', 'Medium', 'Low']
const file = ref('_default')
const fileOptions = ref([{ label: 'Défaut (toutes files)', value: '_default' }])
const edit = reactive({ Urgent: { response: 0, resolution: 0 }, High: { response: 0, resolution: 0 }, Medium: { response: 0, resolution: 0 }, Low: { response: 0, resolution: 0 } })
const saving = ref(false)

function loadFile () {
  const pol = (policies.value && policies.value[file.value]) || {}
  const def = (defaults.value && defaults.value._default) || {}
  for (const pr of PRIORITIES) {
    const cell = pol[pr] || def[pr] || { response: 0, resolution: 0 }
    edit[pr].response = +(((cell.response || 0) / 60).toFixed(2))
    edit[pr].resolution = +(((cell.resolution || 0) / 60).toFixed(2))
  }
}
async function save () {
  saving.value = true
  try {
    const pol = JSON.parse(JSON.stringify(policies.value || {}))
    pol[file.value] = {}
    for (const pr of PRIORITIES) pol[file.value][pr] = { response: Math.round((edit[pr].response || 0) * 60), resolution: Math.round((edit[pr].resolution || 0) * 60) }
    const ok = await savePolicies(pol)
    $q.notify({ type: ok ? 'positive' : 'negative', message: ok ? 'SLA enregistrés (' + (file.value === '_default' ? 'Défaut' : file.value) + ')' : 'Échec de l\'enregistrement' })
  } catch (e) { $q.notify({ type: 'negative', message: e.message }) } finally { saving.value = false }
}
onMounted(async () => {
  await loadPolicies()
  try {
    const types = await listDocs('Issue Type', { fields: ['name'], limit: 100, orderBy: 'name asc' })
    fileOptions.value = [{ label: 'Défaut (toutes files)', value: '_default' }, ...types.map(t => ({ label: t.name, value: t.name }))]
  } catch { /* types optionnels */ }
  loadFile()
})
</script>
