export default {
  id: 'resos-revenue',
  name: 'Revenue by Day',
  category: 'resos',
  categoryLabel: 'ResOS',
  subcategory: 'Revenue',
  description: 'Daily restaurant revenue from ResOS within the selected date range.',

  async run({ dateFrom, dateTo }, { resos }) {
    const data = await resos.callApi('bookings', { date_from: dateFrom, date_to: dateTo, per_page: 500 })
    const bookings = data?.data ?? data?.bookings ?? []

    const byDate = {}
    for (const b of bookings) {
      const date = b.date ?? b.booking_date
      if (!date) continue
      if (!byDate[date]) byDate[date] = { revenue: 0, covers: 0 }
      byDate[date].revenue += parseFloat(b.total ?? b.amount ?? 0) || 0
      byDate[date].covers  += parseInt(b.covers ?? b.party_size ?? 0) || 0
    }

    const rows = Object.entries(byDate)
      .sort(([a], [b]) => a.localeCompare(b))
      .map(([date, g]) => ({
        date,
        covers:       g.covers,
        revenue:      g.revenue.toFixed(2),
        revenue_cover: g.covers > 0 ? (g.revenue / g.covers).toFixed(2) : '0.00',
      }))

    const totalRevenue = rows.reduce((s, r) => s + parseFloat(r.revenue), 0)

    return {
      columns: [
        { key: 'date',          label: 'Date',       type: 'date' },
        { key: 'covers',        label: 'Covers',     type: 'number' },
        { key: 'revenue',       label: 'Revenue',    type: 'currency' },
        { key: 'revenue_cover', label: 'Rev/Cover',  type: 'currency' },
      ],
      rows,
      summary: [
        { label: 'Total revenue', value: totalRevenue.toFixed(2) },
      ],
    }
  },
}
