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

// Authorize (release) a warehouse + shipping methods to a merchant.
// merchant is the raw object from GET /api/ffn/merchants; its id is `userId`.
const props = defineProps({
  merchant: { type: Object, required: true }
})
const emit = defineEmits(['close', 'authorized'])

const loading = ref(false)
const submitting = ref(false)
const warehouses = ref([])
const shippingMethods = ref([])
const selectedWarehouseId = ref('')
const selectedShippingMethodIds = ref([])
const errorMsg = ref('')

const asList = (res) => res?.items || res?.records || (Array.isArray(res) ? res : [])
const merchantId = computed(() => props.merchant?.userId || props.merchant?.merchantId || props.merchant?.id || '')
const merchantName = computed(() => props.merchant?.address?.company || props.merchant?.name || merchantId.value)
const whId = (w) => w?.warehouseId || w?.id || ''
const whLabel = (w) => `${w?.name || ''} (${whId(w)})`.trim()
const smId = (s) => s?.shippingMethodId || s?.id || ''
const smLabel = (s) => `${s?.name || ''} (${smId(s)})`.trim()

const loadOptions = async () => {
  loading.value = true
  errorMsg.value = ''
  try {
    const [whRes, smRes] = await Promise.all([
      $fetch('/api/ffn/warehouses', { headers: useRequestHeaders(['cookie']) }),
      $fetch('/api/ffn/shipping-methods', { headers: useRequestHeaders(['cookie']) })
    ])
    if (Number(whRes?.status || 200) >= 400) errorMsg.value = whRes?.message || 'Failed to load warehouses'
    if (Number(smRes?.status || 200) >= 400) errorMsg.value = smRes?.message || errorMsg.value || 'Failed to load shipping methods'
    warehouses.value = asList(whRes)
    shippingMethods.value = asList(smRes)
    if (warehouses.value.length === 1) selectedWarehouseId.value = whId(warehouses.value[0])
    // Preselect all shipping methods (typical: authorize the warehouse with all its methods)
    selectedShippingMethodIds.value = shippingMethods.value.map(smId).filter(Boolean)
  } catch (err) {
    errorMsg.value = err?.message || 'Failed to load warehouses / shipping methods'
  } finally {
    loading.value = false
  }
}

onMounted(loadOptions)

const canSubmit = computed(() => !!merchantId.value && !!selectedWarehouseId.value && selectedShippingMethodIds.value.length > 0 && !submitting.value)

const submit = async () => {
  if (!canSubmit.value) return
  submitting.value = true
  errorMsg.value = ''
  try {
    const res = await $fetch('/api/ffn/authorizations', {
      method: 'POST',
      headers: useRequestHeaders(['cookie']),
      body: {
        merchantId: merchantId.value,
        warehouseId: selectedWarehouseId.value,
        shippingMethodIds: selectedShippingMethodIds.value
      }
    })
    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 || 'Authorization failed')
      toast({ message: errorMsg.value, type: 'is-danger', duration: 4000 })
      return
    }
    toast({
      message: res?.skipped ? 'Already authorized — nothing to do' : 'Warehouse authorized to merchant',
      type: res?.skipped ? 'is-info' : 'is-success',
      duration: 2500
    })
    emit('authorized')
    emit('close')
  } catch (err) {
    errorMsg.value = err?.data?.message || err?.message || 'Authorization failed'
    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">Authorize warehouse → {{ merchantName }}</p>
        <button class="delete" aria-label="close" @click="emit('close')"></button>
      </header>
      <section class="modal-card-body">
        <p class="mb-3 has-text-grey">Merchant: <code>{{ merchantId || '—' }}</code></p>

        <div v-if="errorMsg" class="notification is-danger is-light">{{ errorMsg }}</div>
        <div v-if="loading">Loading warehouses &amp; shipping methods…</div>

        <template v-else>
          <div class="field">
            <label class="label">Warehouse (Lager)</label>
            <div class="control">
              <div class="select is-fullwidth">
                <select v-model="selectedWarehouseId">
                  <option value="">-- Select warehouse --</option>
                  <option v-for="w in warehouses" :key="whId(w)" :value="whId(w)">{{ whLabel(w) }}</option>
                </select>
              </div>
            </div>
            <p v-if="warehouses.length === 0" class="help is-warning">No warehouses available.</p>
          </div>

          <div class="field">
            <label class="label">Shipping methods (Versandarten)</label>
            <p v-if="shippingMethods.length === 0" class="help is-warning">No shipping methods available.</p>
            <label v-for="s in shippingMethods" :key="smId(s)" class="checkbox is-block mb-1">
              <input type="checkbox" :value="smId(s)" v-model="selectedShippingMethodIds" /> {{ smLabel(s) }}
            </label>
          </div>
        </template>
      </section>
      <footer class="modal-card-foot">
        <button class="button is-primary" :class="{ 'is-loading': submitting }" :disabled="!canSubmit" @click="submit">Authorize</button>
        <button class="button" @click="emit('close')">Cancel</button>
      </footer>
    </div>
  </div>
</template>

<style scoped>
.is-block { display: block; }
code { word-break: break-all; }
</style>
