<?php

namespace App\Domain\Documents\Requirements;

use App\Domain\Applicants\Models\Applicant;
use App\Domain\Documents\Services\ChecklistBuilder;
use App\Domain\Workflow\Requirements\StageRequirement;

/**
 * Stage requirement (§8) contributed by the documents module: the applicant's
 * mandatory checklist must be satisfied before this stage can be entered.
 *
 * Params:
 *   codes  — limit the check to specific document type codes
 *   all    — when true, every mandatory checklist item must be satisfied
 */
class DocumentsVerified implements StageRequirement
{
    public function __construct(private readonly ChecklistBuilder $checklists) {}

    public function type(): string
    {
        return 'documents_verified';
    }

    public function describe(array $params): string
    {
        $codes = $params['codes'] ?? [];

        if ($codes !== []) {
            return 'These documents must be verified: '.implode(', ', $codes).'.';
        }

        return 'All mandatory documents must be verified.';
    }

    public function isSatisfiedBy(Applicant $applicant, array $params): bool
    {
        $checklist = $this->checklists->forApplicant($applicant);
        $codes = $params['codes'] ?? [];

        $items = collect($checklist['items']);

        if ($codes !== []) {
            $items = $items->filter(
                fn (array $item) => in_array($item['document_type']['code'], $codes, true)
            );

            // A named document that no rule requires is not on file at all.
            if ($items->count() < count($codes)) {
                return false;
            }
        } else {
            $items = $items->where('is_mandatory', true);
        }

        return $items->every(fn (array $item) => $item['is_satisfied']);
    }
}
