import { apiRequest } from '../lib/api'
import { getActiveBusinessId } from '../lib/businessContext'

export interface DailyActivityPoint {
  date: string
  count: number
}

export interface DailyActivitySeries {
  days: number
  total: number
  items: DailyActivityPoint[]
}

export interface DualDailyActivityResponse {
  days: number
  primary: DailyActivitySeries
  secondary: DailyActivitySeries
}

function businessPath(resource: 'orders' | 'customers', suffix = '') {
  const businessId = getActiveBusinessId()
  if (!businessId) {
    throw new Error('No active business selected. Please sign in again.')
  }
  return `/businesses/${businessId}/${resource}${suffix}`
}

export async function getOrdersDailyActivity(days = 30, signal?: AbortSignal) {
  return apiRequest<DualDailyActivityResponse>(
    `${businessPath('orders', '/activity')}?days=${days}`,
    { auth: true, signal },
  )
}

export async function getCustomersDailyActivity(days = 30, signal?: AbortSignal) {
  return apiRequest<DualDailyActivityResponse>(
    `${businessPath('customers', '/activity')}?days=${days}`,
    { auth: true, signal },
  )
}
