<?php

namespace App\Console\Commands;

use App\Domain\Notification\Services\PushNotificationService;
use App\Domain\Training\Models\TrainingSession;
use Illuminate\Console\Command;

class SendSessionReminderPush extends Command
{
    protected $signature = 'push:session-reminder {--minutes=30 : Minutes before session to send reminder}';
    protected $description = 'Send push notification to participants about upcoming session';

    public function handle(PushNotificationService $pushService): int
    {
        $minutes = (int) $this->option('minutes');
        $targetTime = now()->addMinutes($minutes);

        $sessions = TrainingSession::where('session_date', now()->toDateString())
            ->where('start_time', '>=', $targetTime->format('H:i:00'))
            ->where('start_time', '<=', $targetTime->addMinute()->format('H:i:00'))
            ->where('status', 'scheduled')
            ->with('group')
            ->get();

        $count = 0;
        foreach ($sessions as $session) {
            $group = $session->group;
            if (!$group) {
                continue;
            }

            $groupName = $group->name_ar ?? 'المجموعة';
            $time = $session->start_time;

            $pushService->sendToGroupParticipants(
                $group,
                'تذكير بالجلسة',
                "جلسة {$groupName} تبدأ خلال {$minutes} دقيقة ({$time})",
                [
                    'type' => 'session_reminder',
                    'session_id' => $session->id,
                    'group_id' => $group->id,
                    'start_time' => $time,
                ],
                'session.reminder'
            );

            $count++;
        }

        $this->info("Sent reminders for {$count} sessions.");

        return self::SUCCESS;
    }
}
