<?php

declare(strict_types=1);

namespace App\Support\Governance\Controls;

final readonly class CanonicalControlResolutionRequest
{
    public function __construct(
        public string $provider,
        public string $consumerContext,
        public ?string $subjectFamilyKey = null,
        public ?string $workload = null,
        public ?string $signalKey = null,
    ) {}

    /**
     * @param  array<string, mixed>  $data
     */
    public static function fromArray(array $data): self
    {
        return new self(
            provider: self::normalize((string) ($data['provider'] ?? '')),
            consumerContext: self::normalize((string) ($data['consumer_context'] ?? '')),
            subjectFamilyKey: self::optionalString($data['subject_family_key'] ?? null),
            workload: self::optionalString($data['workload'] ?? null),
            signalKey: self::optionalString($data['signal_key'] ?? null),
        );
    }

    public function hasDiscriminator(): bool
    {
        return $this->subjectFamilyKey !== null || $this->workload !== null || $this->signalKey !== null;
    }

    /**
     * @return array{provider: string, subject_family_key: ?string, workload: ?string, signal_key: ?string, consumer_context: string}
     */
    public function bindingContext(): array
    {
        return [
            'provider' => $this->provider,
            'subject_family_key' => $this->subjectFamilyKey,
            'workload' => $this->workload,
            'signal_key' => $this->signalKey,
            'consumer_context' => $this->consumerContext,
        ];
    }

    private static function optionalString(mixed $value): ?string
    {
        if (! is_string($value)) {
            return null;
        }

        $normalized = self::normalize($value);

        return $normalized === '' ? null : $normalized;
    }

    private static function normalize(string $value): string
    {
        return trim($value);
    }
}
