<?php

namespace App\Observers;

use App\Facades\Labels;
use Mtc\MercuryDataModels\KeyloopLeaseVehicleVariant;
use Mtc\MercuryDataModels\Label;

class LeaseVehicleObserver
{
    private static $labels = [];

    public function saved(KeyloopLeaseVehicleVariant $vehicle): void
    {
        $this->syncLabels($vehicle);
    }

    public function updating(KeyloopLeaseVehicleVariant $vehicle): void
    {
        $this->syncLabels($vehicle);
    }

    private function syncLabels(KeyloopLeaseVehicleVariant $vehicle)
    {
        if (empty($vehicle->id)) {
            return;
        }

        if (!isset(self::$labels[tenant('id')])) {
            self::$labels[tenant('id')] = Label::query()
                ->where('active', 1)
                ->with('rules')
                ->whereNotNull('data')
                ->get();
        }

        $labels = self::$labels[tenant('id')] ?? collect();

        if ($labels->count() === 0) {
            return;
        }

        // Auto assign
        $labels->filter(fn (Label $label) => !empty($label->data['auto_assign']))
            ->filter(fn ($label) => Labels::shouldAssign($vehicle, $label))
            ->tap(fn ($labels) => $labels->count() && $vehicle->labels()->syncWithoutDetaching($labels->pluck('id')));

        // Auto revoke
        $labels->filter(fn (Label $label) => !empty($label->data['auto_revoke']))
            ->filter(fn ($label) => Labels::shouldRevoke($vehicle, $label))
            ->tap(fn ($labels) => $labels->count() && $vehicle->labels()->detach($labels->pluck('id')));
    }
}
