<?php

declare(strict_types=1);

namespace App\Support\References;

final readonly class ReferenceTechnicalDetail
{
    public function __construct(
        public ?string $displayId,
        public string $fullId,
        public ?string $sourceHint = null,
        public bool $copyable = true,
        public bool $defaultCollapsed = true,
    ) {}

    public static function forIdentifier(
        string $fullId,
        ?string $sourceHint = null,
        bool $copyable = true,
        bool $defaultCollapsed = true,
    ): self {
        return new self(
            displayId: self::displayId($fullId),
            fullId: $fullId,
            sourceHint: $sourceHint,
            copyable: $copyable,
            defaultCollapsed: $defaultCollapsed,
        );
    }

    /**
     * @return array{displayId: ?string, fullId: string, sourceHint: ?string, copyable: bool, defaultCollapsed: bool}
     */
    public function toArray(): array
    {
        return [
            'displayId' => $this->displayId,
            'fullId' => $this->fullId,
            'sourceHint' => $this->sourceHint,
            'copyable' => $this->copyable,
            'defaultCollapsed' => $this->defaultCollapsed,
        ];
    }

    private static function displayId(string $fullId): ?string
    {
        $normalized = preg_replace('/[^a-zA-Z0-9]/', '', $fullId);

        if (! is_string($normalized) || $normalized === '') {
            return null;
        }

        if (mb_strlen($normalized) <= 8) {
            return $normalized;
        }

        return '…'.mb_substr($normalized, -8);
    }
}
