<?php

declare(strict_types=1);

namespace App\Administration\Application\Service;

use App\Administration\Domain\Model\HomeworkRules\HomeworkRules;
use App\Administration\Domain\Model\SchoolCalendar\SchoolCalendar;

use function count;

use DateTimeImmutable;

/**
 * Suggère les prochaines dates d'échéance conformes aux règles de devoirs.
 *
 * Utilisé en mode hard pour proposer des alternatives à l'enseignant
 * quand la date choisie est refusée.
 */
final readonly class ValidDueDateSuggester
{
    private const int MAX_SEARCH_DAYS = 60;

    public function __construct(
        private HomeworkRulesValidator $validator,
    ) {
    }

    /**
     * @return DateTimeImmutable[] Dates conformes triées chronologiquement
     */
    public function suggerer(
        DateTimeImmutable $requestedDate,
        HomeworkRules $rules,
        DateTimeImmutable $creationDate,
        int $maxSuggestions = 3,
        ?SchoolCalendar $calendar = null,
    ): array {
        if (!$rules->estActif()) {
            return [];
        }

        $suggestions = [];
        $checkDate = $requestedDate;

        for ($i = 0; $i < self::MAX_SEARCH_DAYS && count($suggestions) < $maxSuggestions; ++$i) {
            $checkDate = $checkDate->modify('+1 day');

            // Vérifier via le calendrier scolaire (weekends + fériés + vacances)
            if ($calendar !== null) {
                if (!$calendar->estJourOuvre($checkDate)) {
                    continue;
                }
            } elseif ((int) $checkDate->format('N') >= 6) {
                // Fallback : sauter les weekends si pas de calendrier
                continue;
            }

            $result = $this->validator->valider($rules, $checkDate, $creationDate);

            if ($result->estValide()) {
                $suggestions[] = $checkDate;
            }
        }

        return $suggestions;
    }
}
