<?php

namespace App\Console\Commands;

use App\Domain\Notification\Models\PushAnnouncement;
use App\Domain\Notification\Services\AnnouncementBroadcastService;
use Illuminate\Console\Command;

class SendScheduledAnnouncements extends Command
{
    protected $signature = 'push:send-scheduled';
    protected $description = 'Send push announcements that are scheduled and ready';

    public function handle(AnnouncementBroadcastService $broadcastService): int
    {
        $announcements = PushAnnouncement::scheduledAndReady()->get();

        if ($announcements->isEmpty()) {
            $this->info('No scheduled announcements ready to send.');
            return self::SUCCESS;
        }

        $count = 0;
        foreach ($announcements as $announcement) {
            try {
                $broadcastService->send($announcement);
                $count++;
                $this->info("Sent: {$announcement->uuid} ({$announcement->sent_count} devices)");
            } catch (\Throwable $e) {
                $this->error("Failed: {$announcement->uuid} — {$e->getMessage()}");
            }
        }

        $this->info("Completed. Sent {$count}/{$announcements->count()} announcements.");

        return self::SUCCESS;
    }
}
