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

const FILTER_QUERY_KEYS = [
  'departmentId',
  'projectCode',
  'expenseType',
  'supplierId',
  'city',
  'ownerId',
  'sourceType',
  'valueKind'
]

const OPPORTUNITY_QUERY_KEYS = [
  ...FILTER_QUERY_KEYS,
  'status',
  'claimId',
  'createdFrom',
  'createdTo',
  'sort',
  'page',
  'pageSize'
]

function camelizeKey(value) {
  return String(value || '').replace(/_([a-z0-9])/gu, (_, letter) => letter.toUpperCase())
}

export function normalizeAnalyticsValuePayload(value) {
  if (Array.isArray(value)) {
    return value.map((item) => normalizeAnalyticsValuePayload(item))
  }
  if (!value || typeof value !== 'object' || value instanceof Date) {
    return value
  }

  return Object.fromEntries(
    Object.entries(value).map(([key, item]) => [
      camelizeKey(key),
      normalizeAnalyticsValuePayload(item)
    ])
  )
}

function snakeCaseKey(value) {
  return String(value || '').replace(/[A-Z]/gu, (letter) => `_${letter.toLowerCase()}`)
}

function appendQueryValue(search, key, value) {
  if (value === undefined || value === null || value === '') {
    return
  }
  search.set(snakeCaseKey(key), String(value))
}

export function buildCfoValueSearch(options = {}) {
  const search = new URLSearchParams()
  appendQueryValue(search, 'start', options.start)
  appendQueryValue(search, 'end', options.end)
  appendQueryValue(search, 'asOf', options.asOf)
  FILTER_QUERY_KEYS.forEach((key) => appendQueryValue(search, key, options[key]))
  return search
}

export function buildSavingsOpportunitySearch(options = {}) {
  const search = new URLSearchParams()
  OPPORTUNITY_QUERY_KEYS.forEach((key) => appendQueryValue(search, key, options[key]))
  return search
}

function buildMutationBody(payload = {}) {
  if (Array.isArray(payload)) {
    return payload.map((item) => buildMutationBody(item))
  }
  if (!payload || typeof payload !== 'object' || payload instanceof Date) {
    return payload
  }
  return Object.fromEntries(
    Object.entries(payload).map(([key, value]) => [snakeCaseKey(key), buildMutationBody(value)])
  )
}

export async function fetchCfoValueDashboard(options = {}) {
  const search = buildCfoValueSearch(options)
  const suffix = search.size ? `?${search.toString()}` : ''
  const payload = await apiRequest(`/analytics/cfo-value${suffix}`, {
    timeoutMs: Number(options.timeoutMs || 10_000),
    timeoutMessage: '经营价值看板加载超时，请稍后重试。'
  })
  return normalizeAnalyticsValuePayload(payload)
}

export async function fetchSavingsOpportunities(options = {}) {
  const search = buildSavingsOpportunitySearch(options)
  const suffix = search.size ? `?${search.toString()}` : ''
  const payload = await apiRequest(`/savings/opportunities${suffix}`, {
    timeoutMs: Number(options.timeoutMs || 10_000),
    timeoutMessage: '节省机会台账加载超时，请稍后重试。'
  })
  return normalizeAnalyticsValuePayload(payload)
}

export async function fetchSavingsOpportunity(opportunityId, options = {}) {
  const payload = await apiRequest(`/savings/opportunities/${encodeURIComponent(opportunityId)}`, {
    timeoutMs: Number(options.timeoutMs || 10_000),
    timeoutMessage: '节省机会证据链加载超时，请稍后重试。'
  })
  return normalizeAnalyticsValuePayload(payload)
}

export async function executeSavingsOpportunityAction(opportunityId, payload) {
  const response = await apiRequest(`/savings/opportunities/${encodeURIComponent(opportunityId)}/actions`, {
    method: 'POST',
    body: JSON.stringify(buildMutationBody(payload)),
    timeoutMs: 15_000,
    timeoutMessage: '节省机会动作执行超时，可使用同一操作窗口安全重试。'
  })
  return normalizeAnalyticsValuePayload(response)
}

export async function recordSavingsRealization(opportunityId, payload) {
  const response = await apiRequest(`/savings/opportunities/${encodeURIComponent(opportunityId)}/realizations`, {
    method: 'POST',
    body: JSON.stringify(buildMutationBody(payload)),
    timeoutMs: 15_000,
    timeoutMessage: '实际结果写入超时，可使用同一操作窗口安全重试。'
  })
  return normalizeAnalyticsValuePayload(response)
}

export async function executeSavingsRealizationAction(realizationId, payload) {
  const response = await apiRequest(`/savings/realizations/${encodeURIComponent(realizationId)}/actions`, {
    method: 'POST',
    body: JSON.stringify(buildMutationBody(payload)),
    timeoutMs: 15_000,
    timeoutMessage: '财务确认动作执行超时，可使用同一操作窗口安全重试。'
  })
  return normalizeAnalyticsValuePayload(response)
}
