import { createTag as apiCreateTag, updateTag as apiUpdateTag, renameTag as apiRenameTag, deleteTag as apiDeleteTag, updateJob, updateTech } from 'src/api/dispatch'

export function useTagManagement (store) {
  function getTagColor (tagLabel) {
    const t = store.allTags.find(x => x.label === tagLabel)
    return t?.color || '#6b7280'
  }
  async function onCreateTag ({ label, color }) {
    color = color || '#6b7280'
    try {
      const created = await apiCreateTag(label, 'Custom', color)
      if (created) store.allTags.push({ name: created.name, label: created.label, color: created.color || color, category: created.category || 'Custom' })
    } catch (e) {
      if (!store.allTags.some(t => t.label === label))
        store.allTags.push({ name: label, label, color, category: 'Custom' })
    }
  }
  async function onUpdateTag ({ name, color }) {
    try {
      await apiUpdateTag(name, { color })
      const t = store.allTags.find(x => x.name === name || x.label === name)
      if (t) t.color = color
    } catch (_e) { /* update failed */ }
  }
  async function onRenameTag ({ oldName, newName }) {
    try {
      await apiRenameTag(oldName, newName)
      const t = store.allTags.find(x => x.name === oldName || x.label === oldName)
      if (t) { t.name = newName; t.label = newName }
      store.jobs.forEach(j => { j.tags = j.tags.map(tg => tg === oldName ? newName : tg) })
      store.technicians.forEach(tc => { tc.tags = tc.tags.map(tg => tg === oldName ? newName : tg) })
    } catch (_e) { /* rename failed */ }
  }
  async function onDeleteTag (label) {
    try {
      await apiDeleteTag(label)
      store.allTags.splice(store.allTags.findIndex(t => t.label === label || t.name === label), 1)
      store.jobs.forEach(j => { j.tags = j.tags.filter(t => t !== label) })
      store.technicians.forEach(tc => { tc.tags = tc.tags.filter(t => t !== label) })
    } catch (_e) { /* delete failed */ }
  }
  function _serializeTags (arr) {
    return (arr || []).map(t => typeof t === 'string' ? { tag: t } : { tag: t.tag, level: t.level || 0, required: t.required || 0 })
  }
  function persistJobTags (job) {
    updateJob(job.name || job.id, { tags: _serializeTags(job.tagsWithLevel || job.tags) }).catch(() => {})
  }
  function persistTechTags (tech) {
    updateTech(tech.name || tech.id, { tags: _serializeTags(tech.tagsWithLevel || tech.tags) }).catch(() => {})
  }

  return {
    getTagColor, onCreateTag, onUpdateTag, onRenameTag, onDeleteTag,
    _serializeTags, persistJobTags, persistTechTags,
  }
}
