<?php

declare(strict_types=1);

namespace App\Support\References\Resolvers;

use App\Support\References\Contracts\ReferenceResolver;
use App\Support\References\ReferenceClass;
use App\Support\References\ReferenceDescriptor;
use App\Support\References\ReferenceResolutionState;
use App\Support\References\ReferenceTechnicalDetail;
use App\Support\References\ResolvedReference;

final class FallbackReferenceResolver implements ReferenceResolver
{
    public function referenceClass(): ReferenceClass
    {
        return ReferenceClass::Unsupported;
    }

    public function resolve(ReferenceDescriptor $descriptor): ResolvedReference
    {
        $primaryLabel = $descriptor->fallbackLabel;
        $primaryLabel = is_string($primaryLabel) && trim($primaryLabel) !== ''
            ? trim($primaryLabel)
            : 'Unresolved reference';

        $state = $descriptor->fallbackLabel !== null
            ? ReferenceResolutionState::PartiallyResolved
            : ReferenceResolutionState::Unresolved;

        return new ResolvedReference(
            referenceClass: $descriptor->referenceClass,
            rawIdentifier: $descriptor->rawIdentifier,
            primaryLabel: $primaryLabel,
            secondaryLabel: $descriptor->contextValue('secondary_label'),
            state: $state,
            stateLabel: null,
            linkTarget: null,
            technicalDetail: ReferenceTechnicalDetail::forIdentifier(
                fullId: $descriptor->rawIdentifier,
                sourceHint: is_string($descriptor->contextValue('source_hint'))
                    ? $descriptor->contextValue('source_hint')
                    : null,
            ),
            meta: [
                'state_description' => $descriptor->contextValue('state_description'),
            ],
        );
    }
}
