import { apiRequest } from './api.js'

export function fetchExpenseClaims() {
  return apiRequest('/reimbursements/claims')
}

export function fetchApprovalExpenseClaims() {
  return apiRequest('/reimbursements/claims/approvals')
}

export function fetchArchivedExpenseClaims() {
  return apiRequest('/reimbursements/claims/archives')
}

export function fetchExpenseClaimDetail(claimId) {
  return apiRequest(`/reimbursements/claims/${encodeURIComponent(String(claimId || '').trim())}`)
}

export function fetchExpenseClaimBudgetAnalysis(claimId) {
  return apiRequest(`/reimbursements/claims/${encodeURIComponent(String(claimId || '').trim())}/budget-analysis`)
}

export function fetchEmployeeLatestProfile(employeeId, params = {}) {
  const query = new URLSearchParams()
  Object.entries(params || {}).forEach(([key, value]) => {
    const normalized = String(value ?? '').trim()
    if (normalized) {
      query.set(key, normalized)
    }
  })
  const suffix = query.toString() ? `?${query.toString()}` : ''
  return apiRequest(`/employee-profiles/${encodeURIComponent(String(employeeId || '').trim())}/latest${suffix}`)
}

export function fetchCurrentEmployeeLatestProfile(params = {}) {
  const query = new URLSearchParams()
  Object.entries(params || {}).forEach(([key, value]) => {
    const normalized = String(value ?? '').trim()
    if (normalized) {
      query.set(key, normalized)
    }
  })
  const suffix = query.toString() ? `?${query.toString()}` : ''
  return apiRequest(`/employee-profiles/me/latest${suffix}`)
}

export function updateExpenseClaim(claimId, payload = {}) {
  return apiRequest(`/reimbursements/claims/${encodeURIComponent(String(claimId || '').trim())}`, {
    method: 'PATCH',
    body: JSON.stringify(payload)
  })
}

export function calculateTravelReimbursement(payload = {}) {
  return apiRequest('/reimbursements/travel-calculator', {
    method: 'POST',
    body: JSON.stringify(payload)
  })
}

export function createExpenseClaimItem(claimId, payload = {}) {
  return apiRequest(`/reimbursements/claims/${encodeURIComponent(String(claimId || '').trim())}/items`, {
    method: 'POST',
    body: JSON.stringify(payload)
  })
}

export function deleteExpenseClaimItem(claimId, itemId) {
  return apiRequest(`/reimbursements/claims/${encodeURIComponent(String(claimId || '').trim())}/items/${encodeURIComponent(String(itemId || '').trim())}`, {
    method: 'DELETE'
  })
}

export function uploadExpenseClaimItemAttachment(claimId, itemId, file) {
  const formData = new FormData()
  formData.append('file', file)

  return apiRequest(`/reimbursements/claims/${encodeURIComponent(String(claimId || '').trim())}/items/${encodeURIComponent(String(itemId || '').trim())}/attachment`, {
    method: 'POST',
    body: formData,
    contentType: null
  })
}

export function fetchExpenseClaimItemAttachmentMeta(claimId, itemId) {
  return apiRequest(`/reimbursements/claims/${encodeURIComponent(String(claimId || '').trim())}/items/${encodeURIComponent(String(itemId || '').trim())}/attachment/meta`)
}

export function fetchExpenseClaimItemAttachmentPreview(claimId, itemId) {
  return apiRequest(`/reimbursements/claims/${encodeURIComponent(String(claimId || '').trim())}/items/${encodeURIComponent(String(itemId || '').trim())}/attachment/preview`, {
    responseType: 'blob'
  })
}

export function fetchExpenseClaimItemAttachment(claimId, itemId) {
  return apiRequest(`/reimbursements/claims/${encodeURIComponent(String(claimId || '').trim())}/items/${encodeURIComponent(String(itemId || '').trim())}/attachment`, {
    responseType: 'blob'
  })
}

export async function fetchExpenseClaimAttachmentAsset(pathOrUrl) {
  const target = String(pathOrUrl || '').trim()
  if (!target) {
    throw new Error('预览地址为空。')
  }

  if (/^https?:\/\//i.test(target)) {
    const response = await fetch(target)
    if (!response.ok) {
      throw new Error(`预览加载失败（${response.status}）。`)
    }
    return response.blob()
  }

  return apiRequest(target, {
    responseType: 'blob'
  })
}

export function deleteExpenseClaimItemAttachment(claimId, itemId) {
  return apiRequest(`/reimbursements/claims/${encodeURIComponent(String(claimId || '').trim())}/items/${encodeURIComponent(String(itemId || '').trim())}/attachment`, {
    method: 'DELETE'
  })
}

export function updateExpenseClaimItem(claimId, itemId, payload) {
  return apiRequest(`/reimbursements/claims/${encodeURIComponent(String(claimId || '').trim())}/items/${encodeURIComponent(String(itemId || '').trim())}`, {
    method: 'PATCH',
    body: JSON.stringify(payload)
  })
}

export function submitExpenseClaim(claimId) {
  return apiRequest(`/reimbursements/claims/${encodeURIComponent(String(claimId || '').trim())}/submit`, {
    method: 'POST',
    body: JSON.stringify({})
  })
}

export function returnExpenseClaim(claimId, payload = {}) {
  return apiRequest(`/reimbursements/claims/${encodeURIComponent(String(claimId || '').trim())}/return`, {
    method: 'POST',
    body: JSON.stringify(payload)
  })
}

export function approveExpenseClaim(claimId, payload = {}) {
  return apiRequest(`/reimbursements/claims/${encodeURIComponent(String(claimId || '').trim())}/approve`, {
    method: 'POST',
    body: JSON.stringify(payload)
  })
}

export function payExpenseClaim(claimId) {
  return apiRequest(`/reimbursements/claims/${encodeURIComponent(String(claimId || '').trim())}/pay`, {
    method: 'POST',
    body: JSON.stringify({})
  })
}

export function deleteExpenseClaim(claimId) {
  return apiRequest(`/reimbursements/claims/${encodeURIComponent(String(claimId || '').trim())}`, {
    method: 'DELETE'
  })
}
