<?php

namespace App\Listeners;

use App\Events\VehiclePriceChangedDuringStockSync;
use App\Facades\Settings;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\DispatchesJobs;
use Mtc\MercuryDataModels\Services\FinanceService;
use Mtc\MercuryDataModels\Services\FinanceServiceHelper;

class RefreshFinanceOnVehiclePriceChange implements ShouldQueue
{
    use DispatchesJobs;

    public $queue = 'sync';

    public function handle(VehiclePriceChangedDuringStockSync $event): void
    {
        $vehicle = $event->getVehicle();

        // Delete cached finance quotes (keep manual entries)
        $vehicle->financeExamples()
            ->where('provider', '!=', 'manual')
            ->delete();

        // Clear finance fields on vehicle
        $vehicle->update([
            'monthly_price' => null,
            'monthly_cost_type' => null,
        ]);

        // Request new quotes if provider enabled and not using batch updates
        if (FinanceServiceHelper::hasEnabledProvider() && !Settings::get('finance-batch-update')) {
            new FinanceService()->request($vehicle, [], true);
        }
    }
}
