export default {
  id: 'newbook-arrivals',
  name: 'Arrivals',
  category: 'newbook',
  categoryLabel: 'NewBook',
  subcategory: 'Reservations',
  description: 'All bookings with an arrival date within the selected range, including guest name, room, rate, and booking source.',

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

    const rows = (data?.data ?? []).map(b => ({
      ref:        b.booking_ref      ?? b.id,
      guest:      b.guest_name       ?? `${b.first_name ?? ''} ${b.last_name ?? ''}`.trim(),
      arrival:    b.arrival_date,
      departure:  b.departure_date,
      nights:     b.nights           ?? b.no_nights,
      room:       b.site_name        ?? b.room_name ?? b.site_id,
      adults:     b.adults           ?? b.no_adults,
      children:   b.children         ?? b.no_children ?? 0,
      source:     b.booking_source   ?? b.channel,
      status:     b.booking_status   ?? b.status,
      total:      b.booking_total    ?? b.total_price,
    }))

    return {
      columns: [
        { key: 'ref',       label: 'Ref' },
        { key: 'guest',     label: 'Guest' },
        { key: 'arrival',   label: 'Arrival',   type: 'date' },
        { key: 'departure', label: 'Departure', type: 'date' },
        { key: 'nights',    label: 'Nights',    type: 'number' },
        { key: 'room',      label: 'Room' },
        { key: 'adults',    label: 'Adults',    type: 'number' },
        { key: 'children',  label: 'Children',  type: 'number' },
        { key: 'source',    label: 'Source' },
        { key: 'status',    label: 'Status' },
        { key: 'total',     label: 'Total',     type: 'currency' },
      ],
      rows,
      summary: [
        { label: 'Arrivals',     value: String(rows.length) },
        { label: 'Total revenue', value: rows.reduce((s, r) => s + (parseFloat(r.total) || 0), 0).toFixed(2) },
      ],
    }
  },
}
