import { ref, watch } from 'vue'

import { fetchEmployeeLatestProfile } from '../../services/reimbursements.js'

export function useTravelRequestEmployeeRiskProfile({ request, isApplicationDocument }) {
  const employeeRiskProfile = ref(null)
  const employeeRiskProfileLoading = ref(false)
  const employeeRiskProfileError = ref('')
  let employeeRiskProfileLoadSeq = 0

  function resolveProfileLookupId() {
    return String(
      request.value?.profileEmployeeId
      || request.value?.employeeId
      || request.value?.employee_id
      || request.value?.profileName
      || ''
    ).trim()
  }

  function resolveProfileExpenseScope() {
    const typeCode = String(request.value?.typeCode || '').trim()
    return typeCode && !typeCode.endsWith('_application') ? typeCode : 'overall'
  }

  async function loadEmployeeRiskProfile() {
    const employeeId = resolveProfileLookupId()
    if (!employeeId || isApplicationDocument.value) {
      employeeRiskProfile.value = null
      employeeRiskProfileError.value = ''
      employeeRiskProfileLoading.value = false
      return
    }

    const sequence = ++employeeRiskProfileLoadSeq
    employeeRiskProfileLoading.value = true
    employeeRiskProfileError.value = ''
    try {
      const payload = await fetchEmployeeLatestProfile(employeeId, {
        scene: 'approval',
        claim_id: request.value?.claimId || '',
        window_days: 90,
        expense_type_scope: resolveProfileExpenseScope()
      })
      if (sequence === employeeRiskProfileLoadSeq) {
        employeeRiskProfile.value = payload || null
      }
    } catch (error) {
      if (sequence === employeeRiskProfileLoadSeq) {
        employeeRiskProfile.value = null
        employeeRiskProfileError.value = error?.message || '用户画像读取失败'
      }
    } finally {
      if (sequence === employeeRiskProfileLoadSeq) {
        employeeRiskProfileLoading.value = false
      }
    }
  }

  watch(
    () => [
      request.value?.claimId,
      request.value?.profileEmployeeId,
      request.value?.employeeId,
      request.value?.employee_id,
      request.value?.profileName,
      request.value?.typeCode,
      isApplicationDocument.value
    ].join('|'),
    () => {
      void loadEmployeeRiskProfile()
    },
    { immediate: true }
  )

  return {
    employeeRiskProfile,
    employeeRiskProfileError,
    employeeRiskProfileLoading
  }
}
