<?php

declare(strict_types=1);

namespace WPStack\Sandbox\Domain;

use DateInterval;
use DateTimeImmutable;

final class SessionPolicy
{
    public const INITIAL_MINUTES = 6;
    public const EXTENSION_MINUTES = 6;
    public const MAXIMUM_MINUTES = 50;

    public function __construct(
        private int $initialMinutes = self::INITIAL_MINUTES,
        private int $extensionMinutes = self::EXTENSION_MINUTES,
        private int $maximumMinutes = self::MAXIMUM_MINUTES,
        private bool $extensionsAllowed = true
    ) {
        $this->initialMinutes = max(1, $this->initialMinutes);
        $this->extensionMinutes = max(0, $this->extensionMinutes);
        $this->maximumMinutes = max($this->initialMinutes, $this->maximumMinutes);
    }

    public function initialExpiry(DateTimeImmutable $created): DateTimeImmutable
    {
        return $created->add(new DateInterval('PT' . $this->initialMinutes . 'M'));
    }

    public function extendedExpiry(DateTimeImmutable $currentExpiry): ?DateTimeImmutable
    {
        if (!$this->extensionsAllowed || $this->extensionMinutes === 0) {
            return null;
        }

        return $currentExpiry->add(
            new DateInterval('PT' . $this->extensionMinutes . 'M')
        );
    }

    public function capExpiry(
        DateTimeImmutable $created,
        DateTimeImmutable $requested
    ): DateTimeImmutable {
        $maximum = $created->add(
            new DateInterval('PT' . $this->maximumMinutes . 'M')
        );

        return $requested > $maximum ? $maximum : $requested;
    }

    public function isExpired(
        DateTimeImmutable $expires,
        DateTimeImmutable $now
    ): bool {
        return $expires <= $now;
    }
}
