<?php

namespace App\Domain\Facility\Listeners;

use App\Domain\Facility\Events\FacilityStatusChanged;
use App\Domain\Facility\Models\SpaceReservation;
use App\Domain\Notification\Services\NotificationService;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;

class CancelReservationsOnMaintenance implements ShouldQueue
{
    public function __construct(
        private NotificationService $notificationService,
    ) {}

    public function handle(FacilityStatusChanged $event): void
    {
        try {
            // Only act when facility goes to maintenance or closed
            if (!in_array($event->newStatus, ['maintenance', 'closed'])) {
                return;
            }

            $facility = $event->facility;

            // Cancel all FUTURE confirmed/tentative reservations
            $reservations = SpaceReservation::where('facility_id', $facility->id)
                ->where('reservation_date', '>', today())
                ->whereIn('status', ['confirmed', 'tentative'])
                ->get();

            foreach ($reservations as $reservation) {
                $reservation->update([
                    'status' => 'cancelled',
                    'cancelled_by' => $event->actor->id,
                    'cancelled_at' => now(),
                ]);

                // Notify the creator of the reservation
                if ($reservation->created_by) {
                    $this->notificationService->sendSimple(
                        type: 'facility.reservation_cancelled',
                        recipientId: $reservation->created_by,
                        recipientType: 'user',
                        data: [
                            'facility_name' => $facility->name_ar ?? $facility->name,
                            'reservation_date' => $reservation->reservation_date->format('Y-m-d'),
                            'reason' => $event->newStatus === 'maintenance' ? 'صيانة المنشأة' : 'إغلاق المنشأة',
                        ],
                        priority: 'high',
                    );
                }
            }

            Log::info("CancelReservationsOnMaintenance: cancelled {$reservations->count()} reservations for facility {$facility->id}");
        } catch (\Throwable $e) {
            Log::error('CancelReservationsOnMaintenance failed: ' . $e->getMessage(), [
                'facility_id' => $event->facility->id,
                'new_status' => $event->newStatus,
            ]);
        }
    }

    public function failed(FacilityStatusChanged $event, \Throwable $exception): void
    {
        Log::critical('CancelReservationsOnMaintenance PERMANENTLY FAILED', [
            'facility_id' => $event->facility->id,
            'new_status' => $event->newStatus,
            'error' => $exception->getMessage(),
        ]);
    }
}
