<?php
namespace App\Notifications;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;

/** Daily risk digest: severity counts + top exceptions + money at stake. Plain-array
 *  payload so it queue-serializes cleanly. */
class RiskDigest extends Notification implements ShouldQueue
{
    use Queueable;

    public function __construct(public array $digest) {}

    public function via(object $notifiable): array
    {
        return ['mail', 'database'];
    }

    public function toMail(object $notifiable): MailMessage
    {
        $d = $this->digest;
        $m = (new MailMessage)
            ->subject("Nowills risk digest — {$d['crit']} critical, {$d['warn']} warnings ({$d['date']})")
            ->greeting('Morning ' . $notifiable->name . ',')
            ->line("Overnight exception scan: **{$d['crit']} critical**, **{$d['warn']} warnings**, **{$d['opp']} opportunities**. Money at stake: **GH₵" . number_format($d['atRisk']) . '**.');
        foreach (array_slice($d['top'], 0, 6) as $t) {
            $m->line('• [' . $t['sev'] . '] ' . $t['title']);
        }
        return $m->action('Open AI Insights', url('/command#/ai'))
            ->line('Full evidence and recommended actions are in the Command Centre.');
    }

    public function toArray(object $notifiable): array
    {
        $d = $this->digest;
        $top = array_slice(array_map(fn($t) => '[' . $t['sev'] . '] ' . $t['title'], $d['top']), 0, 3);
        return [
            'title' => "Risk digest: {$d['crit']} critical, {$d['warn']} warnings",
            'body' => implode(' · ', $top),
            'url' => '/command#/ai',
            'icon' => '🤖',
            'kind' => 'risk_digest',
        ];
    }
}
