<?php

declare(strict_types=1);

/*
 * This file is part of the Ferienpass package.
 *
 * (c) Richard Henkenjohann <richard@ferienpass.online>
 *
 * For more information visit the project website <https://ferienpass.online>
 * or the documentation under <https://docs.ferienpass.online>.
 */

namespace Ferienpass\CmsBundle\Filter;

/**
 * Resolves the `Wann?` filter presets to a concrete [von, bis] date range
 * that the existing EarliestDateType / LatestDateType filters can apply.
 *
 * Edge case worth knowing about: the "wochenende" preset returns
 * `today → Sunday` when called on a Saturday or Sunday — otherwise the
 * filter would either include past days (Sat seen from Sun) or pre-empty
 * results (Sat already over by Sun evening).
 */
final class WhenPresetResolver
{
    /**
     * @return array{0: ?\DateTimeImmutable, 1: ?\DateTimeImmutable}
     */
    public static function resolve(string $preset, ?\DateTimeImmutable $today = null): array
    {
        $today ??= new \DateTimeImmutable('today', new \DateTimeZone(date_default_timezone_get()));
        $dow = (int) $today->format('N'); // 1=Mon … 7=Sun

        return match ($preset) {
            'heute' => [$today, $today],
            'wochenende' => $dow >= 6
                // Sat or Sun → from today up to (and including) Sun.
                ? [$today, $today->modify('+'.(7 - $dow).' days')]
                // Mon–Fri → the upcoming Sat & Sun.
                : [$today->modify('+'.(6 - $dow).' days'), $today->modify('+'.(7 - $dow).' days')],
            'woche' => [$today, $today->modify('+'.(7 - $dow).' days')],
            // Anchor "last day of this month" to $today rather than the system
            // clock — \DateTimeImmutable's constructor ignores the value of
            // $today and interprets the relative string against time().
            'monat' => [$today, $today->modify('last day of this month')],
            default => [null, null],
        };
    }
}
