import type { ProductApi } from '../services/productService'

export interface ProductMonthActivity {
  monthKey: string
  label: string
  added: number
  updated: number
}

function toMonthKey(iso: string): string {
  const date = new Date(iso)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  return `${year}-${month}`
}

function formatMonthLabel(monthKey: string, locale: string): string {
  const [year, month] = monthKey.split('-').map(Number)
  return new Date(year, month - 1, 1).toLocaleString(locale === 'fa' ? 'fa-IR' : 'en-US', {
    month: 'short',
    calendar: 'gregory',
    numberingSystem: 'latn',
  })
}

export function buildLast12MonthKeys(): string[] {
  const keys: string[] = []
  const now = new Date()

  for (let i = 11; i >= 0; i -= 1) {
    const date = new Date(now.getFullYear(), now.getMonth() - i, 1)
    const year = date.getFullYear()
    const month = String(date.getMonth() + 1).padStart(2, '0')
    keys.push(`${year}-${month}`)
  }

  return keys
}

export function aggregateProductActivity(
  products: ProductApi[],
  locale: string = 'en',
): ProductMonthActivity[] {
  const monthKeys = buildLast12MonthKeys()
  const added = new Map(monthKeys.map((key) => [key, 0]))
  const updated = new Map(monthKeys.map((key) => [key, 0]))

  for (const product of products) {
    const createdKey = toMonthKey(product.createdAt)
    if (added.has(createdKey)) {
      added.set(createdKey, (added.get(createdKey) ?? 0) + 1)
    }

    const createdTime = new Date(product.createdAt).getTime()
    const updatedTime = new Date(product.updatedAt).getTime()
    if (updatedTime > createdTime) {
      const updatedKey = toMonthKey(product.updatedAt)
      if (updated.has(updatedKey)) {
        updated.set(updatedKey, (updated.get(updatedKey) ?? 0) + 1)
      }
    }
  }

  return monthKeys.map((monthKey) => ({
    monthKey,
    label: formatMonthLabel(monthKey, locale),
    added: added.get(monthKey) ?? 0,
    updated: updated.get(monthKey) ?? 0,
  }))
}
