<?php

namespace App\Support\Witness;

use Illuminate\Support\Collection;

/**
 * A questionnaire section (belongs to one of the nine top-level groups),
 * read from config. Immutable value object.
 */
class WitnessSection
{
    /**
     * @param  Collection<int, WitnessQuestion>  $questions
     * @param  array<int, string>  $evidenceCategories
     */
    public function __construct(
        public readonly string $key,
        public readonly string $group,
        public readonly string $title,
        public readonly ?string $description,
        public readonly Collection $questions,
        public readonly array $evidenceCategories = [],
        public readonly bool $sensitive = false,
    ) {}

    public static function fromConfig(array $c): self
    {
        return new self(
            key: $c['key'],
            group: $c['group'],
            title: $c['title'] ?? $c['key'],
            description: $c['description'] ?? null,
            questions: collect($c['questions'] ?? [])
                ->map(static fn (array $q) => WitnessQuestion::fromConfig($q)),
            evidenceCategories: $c['evidence_categories'] ?? [],
            sensitive: (bool) ($c['sensitive'] ?? false),
        );
    }

    public function question(string $key): ?WitnessQuestion
    {
        return $this->questions->firstWhere('key', $key);
    }

    /** @return Collection<int, WitnessQuestion> */
    public function requiredQuestions(): Collection
    {
        return $this->questions->filter->required->values();
    }

    public function acceptsEvidence(): bool
    {
        return $this->evidenceCategories !== [];
    }
}
