<script setup>
import { toast } from 'bulma-toast'

// Create a fulfiller shipping method (Versandart anlegen) -> POST /api/ffn/shipping-methods.
// Schema confirmed from the live API:
//   { shippingMethodId*, name*, shippingType*, carrierCode?, carrierName?, trackingUrlSchema?,
//     cutoffTime?, note?, fulfillerShippingMethodNumber? }
// shippingType "Standard" is a confirmed valid value.
const emit = defineEmits(['close', 'created'])

const submitting = ref(false)
const errorMsg = ref('')
const useRaw = ref(false)
const rawJson = ref('{\n  \n}')

const form = ref({
  shippingMethodId: '',
  name: '',
  shippingType: 'Standard',
  carrierCode: '',
  carrierName: '',
  trackingUrlSchema: '',
  fulfillerShippingMethodNumber: '',
  note: ''
})

const buildPayload = () => {
  if (useRaw.value) return JSON.parse(rawJson.value || '{}')
  const p = { shippingMethodId: form.value.shippingMethodId, name: form.value.name, shippingType: form.value.shippingType }
  for (const k of ['carrierCode', 'carrierName', 'trackingUrlSchema', 'fulfillerShippingMethodNumber', 'note']) {
    if (form.value[k]) p[k] = form.value[k]
  }
  return p
}

const submit = async () => {
  submitting.value = true
  errorMsg.value = ''
  let payload
  try { payload = buildPayload() } catch (e) { errorMsg.value = 'Invalid JSON in advanced editor'; submitting.value = false; return }
  try {
    const res = await $fetch('/api/ffn/shipping-methods', {
      method: 'POST', headers: useRequestHeaders(['cookie']),
      body: { shippingMethod: payload }
    })
    const ok = res?.success === true || (Number(res?.status || 200) < 400 && res?.success !== false)
    if (!ok) {
      const e = res?.error
      errorMsg.value = e ? (typeof e === 'string' ? e : JSON.stringify(e)) : (res?.message || 'Failed to create shipping method')
      toast({ message: errorMsg.value, type: 'is-danger', duration: 4000 })
      return
    }
    toast({ message: 'Shipping method created', type: 'is-success', duration: 2500 })
    emit('created'); emit('close')
  } catch (err) {
    errorMsg.value = err?.data?.message || err?.message || 'Failed to create shipping method'
    toast({ message: errorMsg.value, type: 'is-danger', duration: 4000 })
  } finally {
    submitting.value = false
  }
}
</script>

<template>
  <div class="modal is-active">
    <div class="modal-background" @click="emit('close')"></div>
    <div class="modal-card">
      <header class="modal-card-head">
        <p class="modal-card-title">Create shipping method (Versandart)</p>
        <button class="delete" aria-label="close" @click="emit('close')"></button>
      </header>
      <section class="modal-card-body">
        <div v-if="errorMsg" class="notification is-danger is-light">{{ errorMsg }}</div>
        <label class="checkbox mb-3 is-block"><input type="checkbox" v-model="useRaw" /> Advanced: edit raw JSON payload</label>

        <template v-if="!useRaw">
          <div class="field"><label class="label">Shipping method ID *</label><div class="control"><input class="input" v-model="form.shippingMethodId" placeholder="e.g. your internal id" /></div></div>
          <div class="field"><label class="label">Name *</label><div class="control"><input class="input" v-model="form.name" placeholder="Versand per DHL" /></div></div>
          <div class="columns">
            <div class="column"><div class="field"><label class="label">Shipping type *</label><div class="control"><input class="input" v-model="form.shippingType" placeholder="Standard" /></div></div></div>
            <div class="column"><div class="field"><label class="label">Carrier code</label><div class="control"><input class="input" v-model="form.carrierCode" placeholder="DHL" /></div></div></div>
          </div>
          <div class="columns">
            <div class="column"><div class="field"><label class="label">Carrier name</label><div class="control"><input class="input" v-model="form.carrierName" /></div></div></div>
            <div class="column"><div class="field"><label class="label">Fulfiller number</label><div class="control"><input class="input" v-model="form.fulfillerShippingMethodNumber" /></div></div></div>
          </div>
          <div class="field"><label class="label">Tracking URL schema</label><div class="control"><input class="input" v-model="form.trackingUrlSchema" /></div></div>
        </template>
        <template v-else>
          <div class="field"><label class="label">Raw shipping method payload (JSON)</label><div class="control"><textarea class="textarea" rows="10" v-model="rawJson"></textarea></div></div>
        </template>
      </section>
      <footer class="modal-card-foot">
        <button class="button is-primary" :class="{ 'is-loading': submitting }" @click="submit">Create</button>
        <button class="button" @click="emit('close')">Cancel</button>
      </footer>
    </div>
  </div>
</template>

<style scoped>.is-block { display: block; }</style>
