<?php

declare(strict_types=1);

namespace App\Service\Notification;

use App\Service\PublicHolidayServiceInterface;
use DateTimeImmutable;
use Throwable;

final readonly class WorkingDayCalculator
{
    public function __construct(
        private PublicHolidayServiceInterface $holidays,
    ) {}

    public function isWorkingDay(DateTimeImmutable $date): bool
    {
        $dayOfWeek = (int) $date->format('N'); // 1 (lundi) .. 7 (dimanche)
        if ($dayOfWeek >= 6) {
            return false;
        }

        return !$this->isPublicHoliday($date);
    }

    public function nextWorkingDay(DateTimeImmutable $date): DateTimeImmutable
    {
        $candidate = $date->modify('+1 day')->setTime(0, 0, 0);
        while (!$this->isWorkingDay($candidate)) {
            $candidate = $candidate->modify('+1 day');
        }

        return $candidate;
    }

    private function isPublicHoliday(DateTimeImmutable $date): bool
    {
        try {
            $holidays = $this->holidays->getHolidaysDayByYears('metropole', $date->format('Y'));
        } catch (Throwable) {
            return false;
        }

        return isset($holidays[$date->format('Y-m-d')]);
    }
}
