<?php

declare(strict_types=1);

namespace App\Administration\Domain\Model\AcademicYear;

use App\Administration\Domain\Exception\InvalidPeriodDatesException;
use DateTimeImmutable;

/**
 * Value Object représentant une période scolaire (trimestre ou semestre).
 *
 * Une période a un numéro de séquence, un libellé, et des dates de début/fin.
 * La date de fin doit être strictement postérieure à la date de début.
 */
final readonly class AcademicPeriod
{
    public function __construct(
        public int $sequence,
        public string $label,
        public DateTimeImmutable $startDate,
        public DateTimeImmutable $endDate,
    ) {
        if ($this->endDate <= $this->startDate) {
            throw InvalidPeriodDatesException::endBeforeStart(
                $this->label,
                $this->startDate->format('Y-m-d'),
                $this->endDate->format('Y-m-d'),
            );
        }
    }

    public function containsDate(DateTimeImmutable $date): bool
    {
        $d = $date->format('Y-m-d');

        return $d >= $this->startDate->format('Y-m-d')
            && $d <= $this->endDate->format('Y-m-d');
    }

    public function daysRemaining(DateTimeImmutable $now): int
    {
        $today = $now->format('Y-m-d');

        if ($today > $this->endDate->format('Y-m-d')) {
            return 0;
        }

        if ($today < $this->startDate->format('Y-m-d')) {
            return (int) $this->startDate->diff($this->endDate)->days;
        }

        return (int) $now->setTime(0, 0)->diff($this->endDate->setTime(0, 0))->days;
    }

    public function isPast(DateTimeImmutable $now): bool
    {
        return $now->format('Y-m-d') > $this->endDate->format('Y-m-d');
    }
}
