<?php

namespace App\Console\Commands;

use App\Events\NewsAdded;
use App\Listeners\NotificationsSubscriber;
use App\Models\News;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Symfony\Component\Console\Attribute\AsCommand;

#[AsCommand(name: 'phpvms:email-test', description: 'Send a test notification to admins')]
#[Signature('phpvms:email-test')]
class EmailTest extends Command
{
    /**
     * Execute the console command.
     */
    public function handle(): int
    {
        $this->components->info('Starting Email/Notification Test...');

        $news = null;

        $this->components->task('Creating test news record', function () use (&$news): void {
            $news = News::create([
                'user_id' => 1, // Assuming User ID 1 is your primary admin
                'subject' => 'Test News - '.now()->toDateTimeString(),
                'body'    => 'This is an automated test notification generated by the phpvms:email-test console command.',
            ]);
        });

        $this->components->task('Dispatching notification to subscriber', function () use ($news): void {
            $newsEvent = new NewsAdded($news);

            // Don't dispatch the event everywhere, just to the notification listener.
            $eventHandler = app(NotificationsSubscriber::class);
            $eventHandler->handleNewsAdded($newsEvent);

            $news->delete(); // Clean up the transient test record
        });

        $this->components->info('Test email/notification triggered successfully!');

        return self::SUCCESS;
    }
}
