<?php

namespace App\Domain\Training\Listeners;

use App\Domain\Facility\Models\SpaceReservation;
use App\Domain\Training\Events\SessionCancelled;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;

class CancelLinkedReservation implements ShouldQueue
{
    public function handle(SessionCancelled $event): void
    {
        try {
            SpaceReservation::where('reservable_type', 'training_session')
                ->where('reservable_id', $event->session->id)
                ->where('status', '!=', 'cancelled')
                ->update(['status' => 'cancelled']);
        } catch (\Throwable $e) {
            Log::error('CancelLinkedReservation failed: ' . $e->getMessage(), [
                'session_id' => $event->session->id,
            ]);
        }
    }

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