export default {
  id: 'newbook-bookings-by-source',
  name: 'Bookings by Source',
  category: 'newbook',
  categoryLabel: 'NewBook',
  subcategory: 'Revenue',
  description: 'Breakdown of bookings and revenue grouped by booking source/channel within the selected arrival date range.',

  async run({ dateFrom, dateTo }, { newbook }) {
    const data = await newbook.callApi('bookings_list', {
      arrival_date_from: dateFrom,
      arrival_date_to:   dateTo,
    })

    const bookings = data?.data ?? []
    const grouped = {}

    for (const b of bookings) {
      const source = b.booking_source ?? b.channel ?? 'Unknown'
      if (!grouped[source]) grouped[source] = { bookings: 0, nights: 0, revenue: 0 }
      grouped[source].bookings++
      grouped[source].nights  += parseInt(b.nights ?? b.no_nights ?? 0) || 0
      grouped[source].revenue += parseFloat(b.booking_total ?? b.total_price ?? 0) || 0
    }

    const rows = Object.entries(grouped)
      .sort((a, b) => b[1].revenue - a[1].revenue)
      .map(([source, g]) => ({
        source,
        bookings: g.bookings,
        nights:   g.nights,
        revenue:  g.revenue.toFixed(2),
        avg_rate: g.nights > 0 ? (g.revenue / g.nights).toFixed(2) : '0.00',
      }))

    const totals = rows.reduce((s, r) => ({
      bookings: s.bookings + r.bookings,
      revenue: s.revenue + parseFloat(r.revenue),
    }), { bookings: 0, revenue: 0 })

    return {
      columns: [
        { key: 'source',   label: 'Source' },
        { key: 'bookings', label: 'Bookings', type: 'number' },
        { key: 'nights',   label: 'Nights',   type: 'number' },
        { key: 'revenue',  label: 'Revenue',  type: 'currency' },
        { key: 'avg_rate', label: 'Avg Rate', type: 'currency' },
      ],
      rows,
      summary: [
        { label: 'Total bookings', value: String(totals.bookings) },
        { label: 'Total revenue',  value: totals.revenue.toFixed(2) },
      ],
    }
  },
}
