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

export type MarketTrendsData = {
  trendRows: Array<UTSJSONObject>
  categoryRows: Array<UTSJSONObject>
  seasonalRows: Array<UTSJSONObject>
  priceRows: Array<UTSJSONObject>
  competitionRows: Array<UTSJSONObject>
  startIso: string
  endIso: string
}

export async function fetchMarketTrends(period: string, range?: { start: string; end: string } | null): Promise<MarketTrendsData> {
  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 startDate = toDateOnly(startIso)
  const endDate = toDateOnly(endIso)

  const trendRows = await rpcOrEmptyArray('rpc_analytics_market_trend_daily', {
    p_start: startIso,
    p_end: endIso
  } as UTSJSONObject)

  const categoryRows = await rpcOrEmptyArray('rpc_analytics_category_sales', {
    p_start_date: startDate,
    p_end_date: endDate
  } as UTSJSONObject)

  const seasonalRows = await rpcOrEmptyArray('rpc_analytics_seasonal_trend', {
    p_start_date: startDate,
    p_end_date: endDate
  } as UTSJSONObject)

  const priceRows = await rpcOrEmptyArray('rpc_analytics_price_trend', {
    p_start: startIso,
    p_end: endIso
  } as UTSJSONObject)

  const competitionRows = await rpcOrEmptyArray('rpc_analytics_competition_share', {
    p_start_date: startDate,
    p_end_date: endDate
  } as UTSJSONObject)

  return {
    trendRows,
    categoryRows,
    seasonalRows,
    priceRows,
    competitionRows,
    startIso,
    endIso
  }
}
