<?php

namespace App\Jobs;

use App\Enums\NotificationTypeEnum;
use App\Enums\SessionStatusEnum;
use App\Models\CoachSession;
use App\Models\Member;
use App\Services\NotificationService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class SendSessionRemindersJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    /**
     * Send reminder 30 minutes before session for academy members.
     */
    public function handle(NotificationService $notificationService): void
    {
        $now = now();
        $reminderWindow = $now->copy()->addMinutes(30);

        // Sessions starting in the next 30 minutes
        $sessions = CoachSession::whereDate('session_date', $now->toDateString())
            ->where('status', '!=', SessionStatusEnum::COMPLETED->value)
            ->where('start_time', '>', $now->format('H:i:s'))
            ->where('start_time', '<=', $reminderWindow->format('H:i:s'))
            ->with(['academy.members', 'game', 'coach'])
            ->get();

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

            $gameName  = $session->game?->name ?? __('Session');
            $coachName = $session->coach?->name ?? '';
            $title     = __('Session Reminder');
            $message   = __('Your session for :game with coach :coach starts in 30 minutes at :time.', [
                'game'  => $gameName,
                'coach' => $coachName,
                'time'  => $session->start_time,
            ]);

            // Get members enrolled in this academy
            $members = $academy->members ?? collect();

            foreach ($members as $member) {
                $notificationService->sendToMember(
                    $member,
                    NotificationTypeEnum::SESSION_REMINDER->value,
                    $title,
                    $message,
                    null,
                    ['session_id' => $session->id]
                );
            }
        }
    }
}
