<?php

namespace App\Domain\Shared\Traits;

use Illuminate\Support\Str;

trait ManglesUniqueOnDelete
{
    public static function bootManglesUniqueOnDelete(): void
    {
        static::deleting(function ($model) {
            $suffix = '_del_' . now()->format('ymdHis');

            foreach ($model->getUniqueFieldsToMangle() as $field) {
                if ($model->{$field} !== null) {
                    $model->{$field} = Str::limit($model->{$field}, 200, '') . $suffix;
                }
            }

            $model->saveQuietly();
        });
    }

    public function getUniqueFieldsToMangle(): array
    {
        return $this->uniqueFieldsToMangle ?? [];
    }
}
