<?php

namespace App\Support\Witness;

use Illuminate\Support\Collection;

/**
 * Loads and exposes the witness-statement questionnaire from config
 * (config/witness_statement.php). This is the single place the rest of the
 * feature reads the questionnaire structure from — sections, questions,
 * groups, autofill mappings and generation options — so nothing is hard-coded
 * into components or views.
 */
class WitnessQuestionnaire
{
    /** @var Collection<int, WitnessSection>|null */
    private ?Collection $sections = null;

    public function __construct(private readonly array $config) {}

    public static function make(): self
    {
        return new self(config('witness_statement', []));
    }

    /** @return Collection<int, WitnessSection> */
    public function sections(): Collection
    {
        return $this->sections ??= collect($this->config['sections'] ?? [])
            ->map(static fn (array $s) => WitnessSection::fromConfig($s));
    }

    public function section(string $key): ?WitnessSection
    {
        return $this->sections()->firstWhere('key', $key);
    }

    /** @return array<int, string> Ordered group names. */
    public function groups(): array
    {
        return $this->config['groups']
            ?? $this->sections()->pluck('group')->unique()->values()->all();
    }

    /**
     * Sections belonging to a group, in config order.
     *
     * @return Collection<int, WitnessSection>
     */
    public function sectionsForGroup(string $group): Collection
    {
        return $this->sections()->filter(fn (WitnessSection $s) => $s->group === $group)->values();
    }

    /**
     * All questions flattened, keyed "sectionKey.questionKey" → WitnessQuestion.
     *
     * @return Collection<string, WitnessQuestion>
     */
    public function flatQuestions(): Collection
    {
        return $this->sections()->flatMap(
            fn (WitnessSection $s) => $s->questions->mapWithKeys(
                fn (WitnessQuestion $q) => [$s->key.'.'.$q->key => $q]
            )
        );
    }

    public function findQuestion(string $sectionKey, string $questionKey): ?WitnessQuestion
    {
        return $this->section($sectionKey)?->question($questionKey);
    }

    /**
     * Every autofill mapping as [sectionKey, questionKey, path].
     *
     * @return array<int, array{0:string,1:string,2:string}>
     */
    public function autofillMappings(): array
    {
        $out = [];

        foreach ($this->sections() as $section) {
            foreach ($section->questions as $question) {
                if ($question->autofill) {
                    $out[] = [$section->key, $question->key, $question->autofill];
                }
            }
        }

        return $out;
    }

    /** @return array<int, array<string, mixed>> */
    public function generationOptions(): array
    {
        return $this->config['generation_options'] ?? [];
    }

    public function documentTypeName(): string
    {
        return $this->config['document_type'] ?? 'Witness Statement';
    }

    /** @return array<int, string> */
    public function statuses(): array
    {
        return $this->config['statuses'] ?? ['draft', 'in_review', 'ready', 'generated', 'approved'];
    }
}
