import { computeDateRange } from './dateRange.uts'
import { rpcOrEmptyArray } from './rpc.uts'

export type DeliveryAnalysisData = {
  trendList: Array<UTSJSONObject>
  topList: Array<UTSJSONObject>
  startIso: string
  endIso: string
}

export async function fetchDeliveryAnalysis(period: string, range?: { start: string; end: string } | null): Promise<DeliveryAnalysisData> {
  let startIso: string;
  let endIso: string;

  if (range != null && range.start && range.end) {
    startIso = range.start;
    endIso = range.end;
  } else {
    const computedRange = computeDateRange(period)
    startIso = computedRange.startIso
    endIso = computedRange.endIso
  }

  const trendList = await rpcOrEmptyArray('rpc_delivery_efficiency_daily', {
    p_start: startIso,
    p_end: endIso
  } as any)

  const topList = await rpcOrEmptyArray('rpc_delivery_efficiency_top_drivers', {
    p_start: startIso,
    p_end: endIso,
    p_limit: 10
  } as any)

  return { trendList, topList, startIso, endIso }
}
