import { computed, ref } from 'vue'
import { useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import { useAuthStore } from '@/stores/auth'
import { useAgentApplyStore } from '@/stores/agentApply'

const BROKER_PATH = '/broker'
const APPLY_LIST_PATH = '/agent-apply/list'

/** 非经纪商入口：有待审核则直达申请列表，否则弹出申请说明 */
export function useBrokerEntry() {
  const router = useRouter()
  const authStore = useAuthStore()
  const agentApplyStore = useAgentApplyStore()
  const { memberProfile } = storeToRefs(authStore)
  const { submitting: applySubmitting, submitError: applyError } = storeToRefs(agentApplyStore)

  const showNotBrokerTip = ref(false)
  const brokerEntryChecking = ref(false)

  const isBroker = computed(() => memberProfile.value?.isBroker === true)

  async function handleBrokerClick() {
    if (isBroker.value) {
      await router.push(BROKER_PATH)
      return
    }
    brokerEntryChecking.value = true
    try {
      const pending = await agentApplyStore.hasPendingApply()
      if (pending) {
        await navigateToApplyList()
        return
      }
      agentApplyStore.submitError = null
      showNotBrokerTip.value = true
    } finally {
      brokerEntryChecking.value = false
    }
  }

  /** 进入申请记录页；已在该页时也会重新拉取列表 */
  async function navigateToApplyList() {
    showNotBrokerTip.value = false
    if (router.currentRoute.value.path !== APPLY_LIST_PATH) {
      await router.push(APPLY_LIST_PATH)
    }
    await agentApplyStore.fetchList(1)
  }

  function goApplyList() {
    void navigateToApplyList()
  }

  async function handleApply(): Promise<boolean> {
    try {
      await agentApplyStore.submit()
      await navigateToApplyList()
      return true
    } catch {
      // submitError 已在 store 中设置
      return false
    }
  }

  return {
    isBroker,
    showNotBrokerTip,
    applySubmitting,
    applyError,
    brokerEntryChecking,
    handleBrokerClick,
    goApplyList,
    handleApply,
  }
}
