<?php

namespace App\Console\Commands;

use App\Models\Incident;
use App\Models\NotificationDelivery;
use App\Models\NotificationPreference;
use App\Models\User;
use App\Services\NotificationSender;
use Illuminate\Console\Command;

/**
 * Sends a daily digest to users who have digest_mode enabled.
 *
 * Runs every 10 minutes and only acts on users whose digest_send_at
 * matches the current time slot. Each user receives one email summarising
 * their incidents from the last 24 hours.
 */
class DispatchDigestsCommand extends Command
{
    protected $signature = 'noc:notifications:digest';
    protected $description = 'Send daily incident digest to users in digest mode';

    public function handle(NotificationSender $sender): int
    {
        $now = now();
        $window = $now->copy()->subMinutes(5)->format('H:i');
        $current = $now->format('H:i');

        $prefs = NotificationPreference::where('digest_mode', true)
            ->whereNotNull('digest_send_at')
            ->whereTime('digest_send_at', '>=', $window)
            ->whereTime('digest_send_at', '<=', $current)
            ->with('user')
            ->get();

        $sent = 0;
        foreach ($prefs as $pref) {
            $user = $pref->user;
            if (!$user) continue;

            $incidents = Incident::where('detected_at', '>=', now()->subDay())
                ->orderByDesc('detected_at')
                ->take(50)
                ->get();

            if ($incidents->isEmpty()) continue;

            $subject = "[NOC Daily Digest] {$incidents->count()} incidents in the last 24h";
            $rows = '';
            foreach ($incidents as $i) {
                $rows .= "<tr><td style=\"padding:4px 8px;color:#94A1A8;font-size:11px;\">{$i->detected_at->format('H:i')}</td>"
                       . "<td style=\"padding:4px 8px;color:#E6E8EA;font-size:11px;\">{$i->public_id}</td>"
                       . "<td style=\"padding:4px 8px;color:#E6E8EA;font-size:11px;\">" . htmlspecialchars((string) $i->severity) . "</td>"
                       . "<td style=\"padding:4px 8px;color:#E6E8EA;font-size:11px;\">" . htmlspecialchars($i->title) . "</td>"
                       . "<td style=\"padding:4px 8px;color:#E6E8EA;font-size:11px;\">" . strtoupper((string) $i->status) . "</td></tr>";
            }
            $html = "<h2>HostSeba NOC daily digest</h2><p>{$incidents->count()} incidents in the last 24 hours.</p>"
                  . "<table border=\"1\" cellspacing=\"0\" cellpadding=\"0\" style=\"border-collapse:collapse;border:1px solid #1F262C;\">"
                  . "<tr><th style=\"padding:6px;color:#94A1A8;\">Time</th><th style=\"padding:6px;color:#94A1A8;\">ID</th>"
                  . "<th style=\"padding:6px;color:#94A1A8;\">Severity</th><th style=\"padding:6px;color:#94A1A8;\">Title</th>"
                  . "<th style=\"padding:6px;color:#94A1A8;\">Status</th></tr>{$rows}</table>";

            $delivery = NotificationDelivery::create([
                'channel_key' => 'email',
                'recipient_user_id' => $user->id,
                'recipient_address' => $user->email,
                'status' => NotificationDelivery::STATUS_QUEUED,
                'payload' => ['subject' => $subject, 'text' => "Open the dashboard for full incident list.", 'html' => $html],
            ]);

            $channel = \App\Models\NotificationChannel::where('key', 'email')->first();
            if ($channel) {
                $result = $sender->send($channel, $delivery, $delivery->payload);
                if ($result['ok']) { $delivery->markSent($result['response'] ?? null); $sent++; }
                else $delivery->markFailed($result['error'] ?? 'unknown');
            }
        }

        $this->info("Dispatched {$sent} digest email(s)");
        return self::SUCCESS;
    }
}
