<?php

namespace App\Domain\Shared\Traits;

use Illuminate\Support\Str;

trait ManglesUniqueOnDelete
{
    public static function bootManglesUniqueOnDelete(): void
    {
        static::deleting(function ($model) {
            $suffix = '_d' . $model->id;

            foreach ($model->getUniqueFieldsToMangle() as $field) {
                if ($model->{$field} !== null) {
                    $maxLen = $model->getMangleMaxLength($field);
                    $available = $maxLen - strlen($suffix);
                    $model->{$field} = Str::limit($model->{$field}, max($available, 1), '') . $suffix;
                }
            }

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

    public function getMangleMaxLength(string $field): int
    {
        return $this->mangleMaxLengths[$field] ?? 255;
    }

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