<?php

namespace App\Listeners;

use Carbon\Carbon;
use Illuminate\Support\Facades\Cache;
use Mtc\MercuryDataModels\Replacement;

class WordReplacements
{
    /**
     * Handle the event.
     *
     * @param object $model
     * @return void
     */
    public function handle($eventName, $data)
    {
        $model = $data[0];

        if (method_exists($model, 'replacementsAttributes')) {
            $replacements = $this->getReplacements($model);

            foreach ($replacements as $replacement) {
                foreach ($model->replacementsAttributes() as $attribute) {
                    $model->{$attribute} = preg_replace(
                        '/\b' . preg_quote($replacement->original, '/') . '\b/u',
                        $replacement->replacement,
                        $model->{$attribute}
                    );
                }
            }
        }
    }

    private function getReplacements($model)
    {
        $cache_key = tenant('id') . '-replacements-' . get_class($model);
        return Cache::remember($cache_key, $this->cacheLife(), function () use ($model) {
            return Replacement::query()
                ->where('type', 'global')
                ->orWhere('type', get_class($model))
                ->get();
        });
    }

    private function cacheLife(): Carbon
    {
        return Carbon::now()->addMinutes(app()->environment('production') ? 20 : 0);
    }
}
