// ── Dispatch Preset CRUD — shared resource group presets ─────────────────────
import { BASE_URL } from 'src/config/erpnext'
import { authFetch } from './auth'

async function apiGet (path) {
  const res = await authFetch(BASE_URL + path)
  const data = await res.json()
  if (data.exc) throw new Error(data.exc)
  return data
}

export async function fetchPresets () {
  const data = await apiGet('/api/resource/Dispatch%20Preset?fields=["*"]&limit_page_length=100&order_by=creation+asc')
  return data.data || []
}

export async function createPreset (payload) {
  const res = await authFetch(
    `${BASE_URL}/api/resource/Dispatch%20Preset`,
    { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) },
  )
  const data = await res.json()
  if (data.exc) throw new Error(data.exc)
  return data.data
}

export async function updatePreset (name, payload) {
  const res = await authFetch(
    `${BASE_URL}/api/resource/Dispatch%20Preset/${encodeURIComponent(name)}`,
    { method: 'PUT', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) },
  )
  const data = await res.json()
  if (data.exc) throw new Error(data.exc)
  return data.data
}

export async function deletePreset (name) {
  const res = await authFetch(
    `${BASE_URL}/api/resource/Dispatch%20Preset/${encodeURIComponent(name)}`,
    { method: 'DELETE' },
  )
  if (!res.ok) {
    const data = await res.json().catch(() => ({}))
    throw new Error(data.exception || 'Delete failed')
  }
}
