import api from './client'

export interface TopLevelSummary {
  total_orders: number
  completed_orders: number
  total_revenue: number
  total_rendering_items: number
}

export interface ThroughputPoint {
  week: string
  count: number
  completed: number
}

export interface RevenuePoint {
  month: string
  revenue: number
  order_count: number
}

export interface ProcessingTimeStats {
  avg_submit_to_complete_s: number | null
  avg_submit_to_processing_s: number | null
  p50_s: number | null
  p95_s: number | null
}

export interface ItemStatusBreakdown {
  pending: number
  approved: number
  rejected: number
}

export interface RenderTimeBreakdown {
  avg_stl_s: number | null
  avg_render_s: number | null
  avg_total_s: number | null
  sample_count: number
}

export interface CategoryCount {
  category: string
  count: number
}

export interface ProductCategoryStats {
  unique_products_rendered: number
  total_products: number
  products_with_cad: number
  products_by_category: CategoryCount[]
}

export interface OutputTypeUsagePoint {
  output_type: string
  count: number
}

export interface RenderStatusDistribution {
  pending: number
  processing: number
  completed: number
  failed: number
}

export interface RendererUsagePoint {
  renderer: string
  count: number
}

export interface TopProductEntry {
  pim_id: string
  product_name: string | null
  category: string
  order_count: number
}

export interface CategoryRevenueEntry {
  category: string
  order_count: number
  revenue: number
}

export interface RenderBackendStatsEntry {
  backend: string
  total: number
  completed: number
  failed: number
  avg_render_s: number | null
  p50_render_s: number | null
}

export interface RenderTimeByOutputType {
  output_type: string
  job_count: number
  avg_render_s: number | null
  min_render_s: number | null
  max_render_s: number | null
  p50_render_s: number | null
}

export interface OrdersByUserEntry {
  full_name: string
  email: string
  role: string
  order_count: number
  revenue: number
}

export interface DashboardKPIs {
  summary: TopLevelSummary
  throughput: ThroughputPoint[]
  revenue: RevenuePoint[]
  processing_times: ProcessingTimeStats
  item_status: ItemStatusBreakdown
  render_times: RenderTimeBreakdown
  product_stats: ProductCategoryStats
  output_type_usage: OutputTypeUsagePoint[]
  render_status: RenderStatusDistribution
  renderer_usage: RendererUsagePoint[]
  top_products: TopProductEntry[]
  orders_by_user: OrdersByUserEntry[]
  category_revenue: CategoryRevenueEntry[]
  render_backend_stats: RenderBackendStatsEntry[]
  render_time_by_output_type: RenderTimeByOutputType[]
}

export async function getDashboardKPIs(
  dateFrom?: string,
  dateTo?: string,
): Promise<DashboardKPIs> {
  const params: Record<string, string> = {}
  if (dateFrom) params.date_from = dateFrom
  if (dateTo) params.date_to = dateTo
  const res = await api.get<DashboardKPIs>('/analytics/dashboard', { params })
  return res.data
}
