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

export type CouponAnalysisData = {
  overviewRow: UTSJSONObject | null
  typeList: Array<UTSJSONObject>
  channelList: Array<UTSJSONObject>
  trendList: Array<UTSJSONObject>
  conversionList: Array<UTSJSONObject>
}

export async function fetchCouponAnalysis(period: string, range?: { start: string; end: string } | null): Promise<CouponAnalysisData> {
  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 p_start_date = toDateOnly(startIso)
  const p_end_date = toDateOnly(endIso)

  const params = {
    p_start_date,
    p_end_date
  } as any

  const [overviewRow, typeList, channelList, trendList, conversionList] = await Promise.all([
    rpcOrNull('rpc_analytics_coupon_overview', params),
    rpcOrEmptyArray('rpc_analytics_coupon_by_type', params),
    rpcOrEmptyArray('rpc_analytics_coupon_by_channel', params),
    rpcOrEmptyArray('rpc_analytics_coupon_trend', params),
    rpcOrEmptyArray('rpc_analytics_coupon_conversion', params)
  ])

  return { overviewRow, typeList, channelList, trendList, conversionList }
}
