<?php

namespace App\Console\Commands;

use App\Models\Announcement;
use App\Services\AnnouncementService;
use Illuminate\Console\Command;

class PublishScheduledAnnouncements extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'announcements:publish';

    protected $description = 'Publish scheduled announcements and notify target users';

    public function handle(AnnouncementService $announcementService): void
    {
        $announcements = Announcement::query()
            ->whereNotNull('publish_at')
            ->where('publish_at', '<=', now())
            ->whereNull('notified_at')
            ->get();

        if ($announcements->isEmpty()) {
            $this->info('No pending announcements to publish.');

            return;
        }

        foreach ($announcements as $announcement) {
            $this->info("Publishing: {$announcement->title}");
            $announcementService->notifyTargets($announcement);
        }

        $this->info('All scheduled announcements processed.');
    }
}
