<?php

namespace App\Support\Witness;

/**
 * A single questionnaire question, read from config. Immutable value object.
 */
class WitnessQuestion
{
    /**
     * @param  array<int, string>  $options  Options for select/multiselect.
     * @param  array<int, WitnessQuestion>  $fields  Child fields for a repeater.
     */
    public function __construct(
        public readonly string $key,
        public readonly string $type,
        public readonly string $label,
        public readonly bool $required = false,
        public readonly ?string $help = null,
        public readonly ?string $autofill = null,
        public readonly array $options = [],
        public readonly array $fields = [],
    ) {}

    public static function fromConfig(array $c): self
    {
        return new self(
            key: $c['key'],
            type: $c['type'] ?? 'short_text',
            label: $c['label'] ?? $c['key'],
            required: (bool) ($c['required'] ?? false),
            help: $c['help'] ?? null,
            autofill: $c['autofill'] ?? null,
            options: $c['options'] ?? [],
            fields: array_map(
                static fn (array $f) => self::fromConfig($f),
                $c['fields'] ?? []
            ),
        );
    }

    public function isRepeater(): bool
    {
        return $this->type === 'repeater';
    }

    /**
     * Whether a stored value counts as "answered" for progress/validation.
     */
    public function isAnswered(mixed $value): bool
    {
        if ($value === null) {
            return false;
        }

        if (is_bool($value)) {
            return true;
        }

        if (is_array($value)) {
            return count(array_filter($value, static fn ($v) => $v !== null && $v !== '' && $v !== [])) > 0;
        }

        return trim((string) $value) !== '';
    }
}
