<?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;

            // The session already records which schedule row produced it, and that is
            // the only row whose facility and segments describe this session.
            //
            // Resolving by (group, day_of_week) instead took whichever row sorted
            // first, with no time match and no is_active filter. A group that trains
            // twice on one weekday, or that has a deactivated row sitting beside a
            // live one, got the wrong pitch — silently, in a listener that swallows
            // its own exceptions into a log line.
            $schedule = $session->schedule_id
                ? TrainingSchedule::find($session->schedule_id)
                : TrainingSchedule::where('training_group_id', $session->training_group_id)
                    ->where('day_of_week', $session->session_date->dayOfWeek)
                    ->where('start_time', $session->start_time)
                    ->where('is_active', true)
                    ->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(),
        ]);
    }
}
