import type { Block } from '@/services/api/blocks'
import type { ExplorerStats, ExplorerTransactionTrendPoint } from '@/services/api/stats'

export interface DashboardData {
  stats: ExplorerStats | null
  recentBlocks: Block[]
  recentTransactionTrend: ExplorerTransactionTrendPoint[]
}

export interface DashboardLoaders {
  loadStats: () => Promise<ExplorerStats>
  loadRecentBlocks: () => Promise<Block[]>
  loadRecentTransactionTrend?: () => Promise<ExplorerTransactionTrendPoint[]>
  onError?: (scope: 'stats' | 'blocks' | 'trend', error: unknown) => void
}

export async function loadDashboardData({
  loadStats,
  loadRecentBlocks,
  loadRecentTransactionTrend,
  onError,
}: DashboardLoaders): Promise<DashboardData> {
  const [statsResult, recentBlocksResult, recentTransactionTrendResult] = await Promise.allSettled([
    loadStats(),
    loadRecentBlocks(),
    loadRecentTransactionTrend ? loadRecentTransactionTrend() : Promise.resolve([]),
  ])

  if (statsResult.status === 'rejected') {
    onError?.('stats', statsResult.reason)
  }

  if (recentBlocksResult.status === 'rejected') {
    onError?.('blocks', recentBlocksResult.reason)
  }

  if (recentTransactionTrendResult.status === 'rejected') {
    onError?.('trend', recentTransactionTrendResult.reason)
  }

  return {
    stats: statsResult.status === 'fulfilled' ? statsResult.value : null,
    recentBlocks: recentBlocksResult.status === 'fulfilled' ? recentBlocksResult.value : [],
    recentTransactionTrend:
      recentTransactionTrendResult.status === 'fulfilled' ? recentTransactionTrendResult.value : [],
  }
}
