<?php

namespace App\Listeners;

use Mtc\MercuryDataModels\Enums\VehicleSubscriptionEventType;
use App\Events\VehicleUpdated;
use App\Facades\Feature;
use App\Jobs\SendVehicleSubscriptionNotificationJob;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Support\Facades\Log;
use Mtc\MercuryDataModels\Vehicle;
use Mtc\MercuryDataModels\VehicleSubscription;

class NotifySubscribersOnImagesAdded implements ShouldQueue
{
    public string $queue = 'emails';

    public function handle(VehicleUpdated $event): void
    {
        if (!Feature::isEnabled('vehicle-subscriptions')) {
            return;
        }

        $vehicle = $event->getVehicle();

        if (!$vehicle) {
            return;
        }

        // Only process for used vehicles (not new)
        if ($vehicle->is_new) {
            return;
        }

        $previousImageCount = $event->getPreviousImageCount();
        $currentImageCount = $vehicle->mediaUses()->count();

        // Only notify if images were added (not removed)
        if ($previousImageCount === null || $currentImageCount <= $previousImageCount) {
            return;
        }

        $newImagesCount = $currentImageCount - $previousImageCount;

        Log::info('Images added detected for vehicle', [
            'vehicle_id' => $vehicle->id,
            'previous_count' => $previousImageCount,
            'current_count' => $currentImageCount,
            'new_images' => $newImagesCount,
        ]);

        $subscriptions = VehicleSubscription::query()
            ->where('vehicle_id', $vehicle->id)
            ->where('event_type', VehicleSubscriptionEventType::IMAGES_ADDED->value)
            ->get();

        if ($subscriptions->isEmpty()) {
            return;
        }

        Log::info('Dispatching images added notifications', [
            'vehicle_id' => $vehicle->id,
            'subscription_count' => $subscriptions->count(),
        ]);

        foreach ($subscriptions as $subscription) {
            SendVehicleSubscriptionNotificationJob::dispatch(
                $subscription,
                VehicleSubscriptionEventType::IMAGES_ADDED,
                [
                    'previous_count' => $previousImageCount,
                    'new_count' => $currentImageCount,
                    'images_added' => $newImagesCount,
                ]
            );
        }
    }
}
