export default {
  id: 'samba-sales-summary',
  name: 'Sales Summary',
  category: 'samba',
  categoryLabel: 'SambaPOS',
  subcategory: 'Sales',
  description: 'Daily sales totals from SambaPOS within the selected date range.',

  async run({ dateFrom, dateTo }, { sambapos }) {
    const { sql, pool } = await sambapos.getConnection()

    try {
      const req = pool.request()
      req.input('dateFrom', sql.Date, dateFrom)
      req.input('dateTo',   sql.Date, dateTo)

      const { recordset: rows } = await req.query(`
        SELECT
          CAST(Date AS DATE)                AS sale_date,
          COUNT(*)                          AS ticket_count,
          SUM(TotalAmount)                  AS gross_total,
          SUM(DiscountAmount)               AS discount_total,
          SUM(TotalAmount - DiscountAmount) AS net_total
        FROM Tickets
        WHERE CAST(Date AS DATE) BETWEEN @dateFrom AND @dateTo
          AND IsCancelled = 0
        GROUP BY CAST(Date AS DATE)
        ORDER BY CAST(Date AS DATE)
      `)

      const totalNet = rows.reduce((s, r) => s + parseFloat(r.net_total ?? 0), 0)

      return {
        columns: [
          { key: 'sale_date',      label: 'Date',      type: 'date' },
          { key: 'ticket_count',   label: 'Tickets',   type: 'number' },
          { key: 'gross_total',    label: 'Gross',     type: 'currency' },
          { key: 'discount_total', label: 'Discounts', type: 'currency' },
          { key: 'net_total',      label: 'Net Total', type: 'currency' },
        ],
        rows: rows.map(r => ({
          sale_date:      r.sale_date instanceof Date ? r.sale_date.toISOString().split('T')[0] : String(r.sale_date).slice(0, 10),
          ticket_count:   r.ticket_count,
          gross_total:    parseFloat(r.gross_total    ?? 0).toFixed(2),
          discount_total: parseFloat(r.discount_total ?? 0).toFixed(2),
          net_total:      parseFloat(r.net_total      ?? 0).toFixed(2),
        })),
        summary: [
          { label: 'Total net', value: totalNet.toFixed(2) },
        ],
      }
    } finally {
      await pool.close()
    }
  },
}
