<?php

declare(strict_types=1);

namespace App\Administration\Application\Service\Import;

use DateTimeImmutable;

/**
 * Parse des dates dans les formats courants utilisés par les fichiers d'import.
 */
final class DateParser
{
    private const array FORMATS = ['d/m/Y', 'Y-m-d', 'd-m-Y', 'd.m.Y'];

    public static function parse(?string $date): ?DateTimeImmutable
    {
        if ($date === null || trim($date) === '') {
            return null;
        }

        $trimmed = trim($date);

        foreach (self::FORMATS as $format) {
            $parsed = DateTimeImmutable::createFromFormat($format, $trimmed);
            if ($parsed !== false && $parsed->format($format) === $trimmed) {
                return $parsed;
            }
        }

        return null;
    }
}
