<?php

declare(strict_types=1);

namespace App\Support\References\Resolvers;

use App\Support\References\ReferenceClass;
use App\Support\References\ReferenceDescriptor;
use App\Support\References\ResolvedReference;
use Illuminate\Support\Str;

final class PrincipalReferenceResolver extends BaseReferenceResolver
{
    public function __construct(
        \App\Support\References\ReferenceTypeLabelCatalog $typeLabels,
    ) {
        parent::__construct($typeLabels);
    }

    public function referenceClass(): ReferenceClass
    {
        return ReferenceClass::Principal;
    }

    public function resolve(ReferenceDescriptor $descriptor): ResolvedReference
    {
        $principalType = $this->contextString($descriptor, 'principal_type');
        $secondaryLabel = $principalType !== null ? Str::headline(str_replace('_', ' ', $principalType)) : 'Principal';

        if (is_string($descriptor->fallbackLabel) && trim($descriptor->fallbackLabel) !== '') {
            return $this->externalLimited($descriptor, primaryLabel: $descriptor->fallbackLabel, secondaryLabel: $secondaryLabel);
        }

        return $this->unresolved($descriptor, primaryLabel: $secondaryLabel, secondaryLabel: $secondaryLabel);
    }
}
