export const APPROVAL_TASK_ROUTE_QUERY_KEYS = Object.freeze([
  'dc_review_page',
  'dc_review_page_size',
  'dc_review_q',
  'dc_review_risk',
  'dc_review_sla'
])

const ALLOWED_PAGE_SIZES = new Set([10, 20])
const ALLOWED_RISK_LEVELS = new Set(['critical', 'high', 'medium', 'low'])
const ALLOWED_SLA_STATES = new Set(['due_soon', 'overdue', 'escalated'])

function readText(source, key) {
  const value = source?.[key]
  return String(Array.isArray(value) ? value[0] || '' : value || '').trim()
}

function positiveInteger(value, fallback) {
  const number = Math.trunc(Number(value))
  return Number.isFinite(number) && number > 0 ? number : fallback
}

export function normalizeApprovalTaskRouteState(state = {}) {
  const filters = state.filters || {}
  const riskLevel = String(filters.riskLevel || filters.risk_level || '').trim()
  const slaState = String(filters.slaState || filters.sla_state || '').trim()
  const pageSize = positiveInteger(state.pageSize || state.page_size, 20)
  return {
    page: positiveInteger(state.page, 1),
    pageSize: ALLOWED_PAGE_SIZES.has(pageSize) ? pageSize : 20,
    filters: {
      keyword: String(filters.keyword || '').trim(),
      riskLevel: ALLOWED_RISK_LEVELS.has(riskLevel) ? riskLevel : '',
      slaState: ALLOWED_SLA_STATES.has(slaState) ? slaState : ''
    }
  }
}

export function readApprovalTaskRouteState(query = {}) {
  return normalizeApprovalTaskRouteState({
    page: readText(query, 'dc_review_page'),
    pageSize: readText(query, 'dc_review_page_size'),
    filters: {
      keyword: readText(query, 'dc_review_q'),
      riskLevel: readText(query, 'dc_review_risk'),
      slaState: readText(query, 'dc_review_sla')
    }
  })
}

export function appendApprovalTaskRouteQuery(query = {}, state = {}) {
  const normalized = normalizeApprovalTaskRouteState(state)
  if (normalized.page > 1) query.dc_review_page = String(normalized.page)
  if (normalized.pageSize !== 20) query.dc_review_page_size = String(normalized.pageSize)
  if (normalized.filters.keyword) query.dc_review_q = normalized.filters.keyword
  if (normalized.filters.riskLevel) query.dc_review_risk = normalized.filters.riskLevel
  if (normalized.filters.slaState) query.dc_review_sla = normalized.filters.slaState
  return query
}
