<script setup>
const props = defineProps({
  modelValue: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update:modelValue', 'change'])

const organizations = useCookie('logship_organizations')
const role = useCookie('logship_role')
const clientIdCookie = useCookie('logship_client_id')
const roleIdCookie = useCookie('logship_role_id')

const isAdmin = computed(() => {
  try {
    const r = typeof role.value === 'string' ? JSON.parse(role.value) : role.value
    return r?.IsClientAdministrator === true
  } catch {
    return false
  }
})

const orgList = computed(() => {
  const orgs = organizations.value || []
  return Array.isArray(orgs) ? orgs : []
})

// Users who auto-login (skipping /select-role) never get logship_organizations
// populated. Fetch the same list select-role.vue uses so the dropdown isn't empty.
const loadOrganizations = async () => {
  if (Array.isArray(organizations.value) && organizations.value.length) return
  if (!clientIdCookie.value || !roleIdCookie.value) return
  try {
    const res = await $fetch(`/api/idempiere-auth/organizations/${clientIdCookie.value}/${roleIdCookie.value}`, {
      headers: useRequestHeaders(['cookie'])
    })
    if (Array.isArray(res) && res.length) {
      organizations.value = res
    }
  } catch (e) {
    console.error('Error loading organizations:', e)
  }
}

onMounted(() => { loadOrganizations() })

const onChange = (e) => {
  const val = e.target.value
  const org = orgList.value.find((o) => String(o.id) === String(val))
  emit('update:modelValue', val)
  emit('change', { id: val, name: org?.name || org?.identifier || '' })
}
</script>

<template>
  <div v-if="isAdmin && orgList.length > 1" class="select is-small">
    <select :value="modelValue" @change="onChange">
      <option value="">All Organizations</option>
      <option v-for="org in orgList" :key="org.id" :value="org.id">
        {{ org.name || org.identifier || org.id }}
      </option>
    </select>
  </div>
</template>
