<?php

namespace App\Observers;

use Mtc\ContentManager\Contracts\MediaUse;
use Mtc\MercuryDataModels\NewCar;
use Mtc\MercuryDataModels\NewCarContent;
use Mtc\MercuryDataModels\NewCarContentHistory;
use Mtc\Stemmer\Stemmer;

class NewCarObserver
{
    /**
     * Actions to do when deleting offer
     *
     * @param NewCar $car
     * @return void
     */
    public function deleting(NewCar $car)
    {
        $car->content->each(fn(NewCarContent $content) => $content->delete());
        $car->versions->each(fn(NewCarContentHistory $version) => $version->delete());
        $car->mediaUses->each(fn(MediaUse $mediaUse) => $mediaUse->delete());
    }

    public function saving(NewCar $car)
    {
        $this->setSearchableContent($car);
    }

    private function setSearchableContent(NewCar $car): void
    {
        $fields = [
            'make_id',
            'model_id',
            'name',
            'derivative',
            'body_style_id',
        ];

        if ($car->isDirty($fields) === false) {
            return;
        }

        $car->search_content = collect([
            'make_id' => $car->make?->name,
            'model_id' => $car->model?->name,
            'title' => $car->name,
            'derivative' => $car->derivative,
            'body_style_id' => $car->bodyStyle?->name,
        ])->filter()
            ->map(fn (string $value) => Stemmer::multiStem($value))
            ->push($car->slug)
            ->flatten()
            ->implode(' ');
    }
}
