<?php

namespace App\Console\Commands;

use App\Enums\GuestNotificationAudience;
use App\Enums\GuestNotificationType;
use App\Models\Event;
use App\Services\GuestNotificationService;
use Illuminate\Console\Command;

class SendGuestFeedbackReminders extends Command
{
    protected $signature = 'guest:feedback-reminders {--hours=4 : Minimum hours after event date before reminding} {--limit=50 : Maximum events to process}';

    protected $description = 'Send feedback reminder notifications to guests of recently finished events';

    public function __construct(private readonly GuestNotificationService $notifications)
    {
        parent::__construct();
    }

    public function handle(): int
    {
        $hours = max(0, (int) $this->option('hours'));
        $limit = max(1, (int) $this->option('limit'));
        $cutoff = now()->subHours($hours);

        $events = Event::query()
            ->where('status', 'published')
            ->where('is_active', true)
            ->whereNotNull('date')
            ->where('date', '<=', $cutoff)
            ->whereDoesntHave('guestNotifications', function ($query) {
                $query->where('type', GuestNotificationType::FEEDBACK_REQUEST->value);
            })
            ->orderBy('date')
            ->limit($limit)
            ->get();

        $count = 0;

        foreach ($events as $event) {
            $title = 'Danke fürs Mitmachen – wie war dein Erlebnis?';
            $body = 'Teile dein kurzes Feedback mit dem Gastgeber oder lade deine Lieblingsmomente noch einmal hoch.';

            $this->notifications->createNotification(
                $event,
                GuestNotificationType::FEEDBACK_REQUEST,
                $title,
                $body,
                [
                    'audience_scope' => GuestNotificationAudience::ALL,
                    'expires_at' => now()->addHours(12),
                ]
            );

            $count++;
        }

        $this->info(sprintf('Feedback reminders dispatched for %d event(s).', $count));

        return Command::SUCCESS;
    }
}
