<?php
declare(strict_types=1);

namespace Ekesto\CacheInvalidator\Integrations\Builders;

/**
 * Immutable scan profile for one post.
 */
final class BuildersScanProfile
{
    private string $builderKey;

    private string $confidence;

    /**
     * @var string[]
     */
    private array $fieldsToScan;

    /**
     * @var string[]
     */
    private array $detectionSignals;

    /**
     * Build a scan profile value object.
     *
     * @param string   $builderKey Builder key.
     * @param string   $confidence Confidence level.
     * @param string[] $fieldsToScan Fields to scan.
     * @param string[] $detectionSignals Detection signals.
     */
    public function __construct(string $builderKey, string $confidence, array $fieldsToScan, array $detectionSignals = [])
    {
        $this->builderKey = sanitize_key($builderKey);
        $this->confidence = in_array($confidence, ['certain', 'likely', 'unknown'], true) ? $confidence : 'unknown';

        $normalizedFields = [];
        foreach ($fieldsToScan as $field) {
            $fieldKey = (string) $field;
            if ($fieldKey === '') {
                continue;
            }
            $normalizedFields[] = $fieldKey;
        }

        if (!in_array('post_content', $normalizedFields, true)) {
            array_unshift($normalizedFields, 'post_content');
        }

        $this->fieldsToScan = array_values(array_unique($normalizedFields));
        $this->detectionSignals = array_values(array_unique(array_filter(array_map('strval', $detectionSignals))));
    }

    /**
     * Return profile builder key.
     *
     * @return string
     */
    public function builderKey(): string
    {
        return $this->builderKey;
    }

    /**
     * Return confidence level.
     *
     * @return string
     */
    public function confidence(): string
    {
        return $this->confidence;
    }

    /**
     * Return fields to scan.
     *
     * @return string[]
     */
    public function fieldsToScan(): array
    {
        return $this->fieldsToScan;
    }

    /**
     * Return detection signals.
     *
     * @return string[]
     */
    public function detectionSignals(): array
    {
        return $this->detectionSignals;
    }
}
