<?php

namespace App\Domain\Workflow\Requirements\Checks;

use App\Domain\Applicants\Models\Applicant;
use App\Domain\Workflow\Requirements\StageRequirement;

/**
 * Age limits, either fixed on the stage or taken from the selected job demand.
 */
class AgeWithinRange implements StageRequirement
{
    public function type(): string
    {
        return 'age_within_range';
    }

    public function describe(array $params): string
    {
        if ($params['from_job_demand'] ?? false) {
            return 'The applicant must fall within the age range of the selected job demand.';
        }

        $min = $params['minimum'] ?? null;
        $max = $params['maximum'] ?? null;

        return trim(sprintf(
            'The applicant must be %s%s%s.',
            $min ? "at least {$min}" : '',
            $min && $max ? ' and ' : '',
            $max ? "at most {$max}" : '',
        ));
    }

    public function isSatisfiedBy(Applicant $applicant, array $params): bool
    {
        $age = $applicant->age();

        if ($age === null) {
            return false;
        }

        if ($params['from_job_demand'] ?? false) {
            $demand = $applicant->jobDemand;

            if ($demand === null) {
                return false;
            }

            return ($demand->minimum_age === null || $age >= $demand->minimum_age)
                && ($demand->maximum_age === null || $age <= $demand->maximum_age);
        }

        $minimum = $params['minimum'] ?? null;
        $maximum = $params['maximum'] ?? null;

        return ($minimum === null || $age >= (int) $minimum)
            && ($maximum === null || $age <= (int) $maximum);
    }
}
