<?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((string) $replacement->original, '/') . '\b/u',
                        (string) $replacement->replacement,
                        (string) $model->{$attribute}
                    );
                }
            }
        }
    }

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

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