export default {
  id: 'internal-run-history',
  name: 'Report Run History',
  category: 'internal',
  categoryLabel: 'Internal',
  subcategory: 'Audit',
  description: 'Log of all reports run within the selected date range, including who ran them and how many rows were returned.',

  async run({ dateFrom, dateTo }, { db }) {
    const { rows } = await db.query(`
      SELECT
        ran_at,
        user_email,
        report_name,
        date_from,
        date_to,
        row_count,
        duration_ms,
        error
      FROM report_runs
      WHERE ran_at::date BETWEEN $1 AND $2
      ORDER BY ran_at DESC
      LIMIT 500
    `, [dateFrom, dateTo])

    return {
      columns: [
        { key: 'ran_at',      label: 'Run At',   type: 'datetime' },
        { key: 'user_email',  label: 'User' },
        { key: 'report_name', label: 'Report' },
        { key: 'date_from',   label: 'From',     type: 'date' },
        { key: 'date_to',     label: 'To',       type: 'date' },
        { key: 'row_count',   label: 'Rows',     type: 'number' },
        { key: 'duration_ms', label: 'ms',       type: 'number' },
        { key: 'error',       label: 'Error' },
      ],
      rows: rows.map(r => ({
        ran_at:      r.ran_at instanceof Date ? r.ran_at.toISOString().replace('T', ' ').slice(0, 19) : r.ran_at,
        user_email:  r.user_email,
        report_name: r.report_name,
        date_from:   r.date_from ? String(r.date_from).slice(0, 10) : '',
        date_to:     r.date_to   ? String(r.date_to).slice(0, 10)   : '',
        row_count:   r.row_count  ?? '',
        duration_ms: r.duration_ms ?? '',
        error:       r.error ?? '',
      })),
      summary: [
        { label: 'Total runs', value: String(rows.length) },
      ],
    }
  },
}
