import { getSDKConfig } from 'config'

import {
  Analytics,
  AggregatedView,
  AggregatedModuleClickWithMetadata,
  TimeFrame
} from '@komi-app/analytics-sdk'

export type AnalyticResponse = {
  clicks: AggregatedModuleClickWithMetadata[]
  views: AggregatedView[]
  pageCTR: number
}

export default class AnalyticsService {
  private analytics: Analytics
  constructor() {
    const analyticsConfig = getSDKConfig('analytics')
    this.analytics = new Analytics(analyticsConfig)
  }

  init(profileId: string) {
    this.analytics.init(profileId)
  }

  getStats = async (timeframe: TimeFrame): Promise<AnalyticResponse> => {
    try {
      return (await this.analytics.getStats({ timeframe })) as AnalyticResponse
    } catch (err) {
      console.error(err)
      return {
        clicks: [],
        views: [],
        pageCTR: 0
      }
    }
  }
}
