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

class NotifySubscribersOnVideoAdded 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;
        }

        $previousVideoCount = $event->getPreviousVideoCount();
        $currentVideoCount = $vehicle->video_count;

        // Only notify if videos were added (not removed) and there was no video before
        if ($previousVideoCount === null || $previousVideoCount > 0 || $currentVideoCount <= 0) {
            return;
        }

        Log::info('Video added detected for vehicle', [
            'vehicle_id' => $vehicle->id,
            'previous_count' => $previousVideoCount,
            'current_count' => $currentVideoCount,
        ]);

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

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

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

        foreach ($subscriptions as $subscription) {
            SendVehicleSubscriptionNotificationJob::dispatch(
                $subscription,
                VehicleSubscriptionEventType::VIDEO_ADDED,
                [
                    'previous_count' => $previousVideoCount,
                    'new_count' => $currentVideoCount,
                ]
            );
        }
    }
}
