<?php

namespace App\Traits;

use App\Events\VehiclePriceChangedDuringStockSync;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Event;
use Mtc\MercuryDataModels\Vehicle;

trait StockSyncTraits
{
    use MapsTaxonomies;

    private function priceChangeEvents(Vehicle $vehicle, string $provider): void
    {
        Event::dispatch(new VehiclePriceChangedDuringStockSync($vehicle, $provider));
    }

    private function removeOld(Collection $allRecords): void
    {
        Vehicle::query()
            ->where('stock_provider', self::NAME)
            ->whereNotIn('uuid', $allRecords)
            ->delete();
    }

    private function removeNotSynced(bool $check_pending = true): void
    {
        if ($this->enoughVehiclesSyncedRecently(config('automotive.sync_margin_for_removing'), $check_pending)) {
            Vehicle::query()
                ->where('stock_provider', $this->getProviderName())
                ->where('was_recently_synced', 0)
                ->when($check_pending, fn($query) => $query->whereNull('pending_stock_sync'))
                ->delete();
        }
    }

    private function enoughVehiclesSyncedRecently(float $margin, bool $check_pending): bool
    {
        $synced = Vehicle::query()
            ->where('stock_provider', $this->getProviderName())
            ->when($check_pending, fn($query) => $query->whereNull('pending_stock_sync'))
            ->where('was_recently_synced', 1)
            ->count();

        $provider_total = Vehicle::query()
            ->where('stock_provider', $this->getProviderName())
            ->when($check_pending, fn($query) => $query->whereNull('pending_stock_sync'))
            ->count();

        return ($synced / $provider_total) > $margin;
    }
}
