import type { RouteLocation } from 'vue-router'
import { ApiClient } from './base'
import { getSelectedProfile } from './profile'

export interface TimeSeriesPoint {
  x: number
  y: number
}

export interface AccountBalanceData {
  accountId: number
  data: TimeSeriesPoint[]
}

export interface BalanceTimeSeriesAnalytics {
  accounts: AccountBalanceData[]
  totals: TimeSeriesPoint[]
}

export interface CategorySpendData {
  categoryId: number | null
  categoryName: string | null
  categoryColor: string | null
  parentCategoryId: number | null
  amount: number
}

export class AnalyticsApiClient extends ApiClient {
  readonly profileName: string
  readonly path: string

  constructor(route: RouteLocation) {
    super()
    this.profileName = getSelectedProfile(route)
    this.path = `/profiles/${this.profileName}/analytics`
  }

  getBalanceTimeSeries(
    currencyCode: string,
    fromTimestampMs: number | null,
    toTimestampMs: number | null,
  ): Promise<BalanceTimeSeriesAnalytics> {
    const params = new URLSearchParams()
    params.append('currency', currencyCode)
    if (fromTimestampMs !== null) {
      params.append('from', fromTimestampMs + '')
    }
    if (toTimestampMs !== null) {
      params.append('to', toTimestampMs + '')
    }
    return super.getJson(this.path + '/balance-time-series?' + params.toString())
  }

  getCategorySpend(
    currencyCode: string,
    fromTimestampMs: number | null,
    toTimestampMs: number | null,
    parentCategoryId: number | null,
  ): Promise<CategorySpendData[]> {
    const params = new URLSearchParams()
    params.append('currency', currencyCode)
    if (fromTimestampMs !== null) {
      params.append('from', fromTimestampMs + '')
    }
    if (toTimestampMs !== null) {
      params.append('to', toTimestampMs + '')
    }
    if (parentCategoryId !== null) {
      params.append('parentId', parentCategoryId + '')
    }
    return super.getJson(this.path + '/category-spend?' + params.toString())
  }
}
