<?php

namespace App\Domain\Training\Listeners;

use App\Domain\Facility\Services\ReservationService;
use App\Domain\Training\Events\SessionCreated;
use App\Domain\Training\Models\TrainingSchedule;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;

class CreateAutoReservation implements ShouldQueue
{
    public function __construct(
        private ReservationService $reservationService,
    ) {}

    public function handle(SessionCreated $event): void
    {
        try {
            $session = $event->session;
            $schedule = TrainingSchedule::where('training_group_id', $session->training_group_id)
                ->where('day_of_week', $session->session_date->dayOfWeek)
                ->first();

            if (!$schedule || !$schedule->facility_id) {
                return;
            }

            $this->reservationService->autoReserveForSession($session, $schedule);
        } catch (\Throwable $e) {
            Log::error('CreateAutoReservation failed: ' . $e->getMessage(), [
                'session_id' => $event->session->id,
            ]);
        }
    }

    public function failed(SessionCreated $event, \Throwable $exception): void
    {
        Log::critical('CreateAutoReservation PERMANENTLY FAILED', [
            'session_id' => $event->session->id,
            'error' => $exception->getMessage(),
        ]);
    }
}
