<?php

namespace MintyPHP\Service\Settings;

class SettingsSessionGateway
{
    private const IDLE_TIMEOUT_MINUTES_FALLBACK = 30;
    private const ABSOLUTE_TIMEOUT_HOURS_FALLBACK = 8;
    private const IDLE_TIMEOUT_MINUTES_MIN = 5;
    private const IDLE_TIMEOUT_MINUTES_MAX = 1440;
    private const ABSOLUTE_TIMEOUT_HOURS_MIN = 1;
    private const ABSOLUTE_TIMEOUT_HOURS_MAX = 72;

    public function __construct(private readonly SettingsMetadataGateway $settingsMetadataGateway)
    {
    }

    public function getSessionIdleTimeoutMinutes(): int
    {
        $value = $this->settingsMetadataGateway->getInt(SettingKeys::SESSION_IDLE_TIMEOUT_MINUTES_KEY);
        if ($value !== null && $this->isValidIdleTimeout($value)) {
            return $value;
        }

        return self::IDLE_TIMEOUT_MINUTES_FALLBACK;
    }

    public function setSessionIdleTimeoutMinutes(?int $minutes, ?string $description = null): bool
    {
        $value = $minutes ?? self::IDLE_TIMEOUT_MINUTES_FALLBACK;
        if (!$this->isValidIdleTimeout($value)) {
            return false;
        }

        $desc = $description ?? 'setting.session_idle_timeout_minutes';
        return $this->settingsMetadataGateway->set(SettingKeys::SESSION_IDLE_TIMEOUT_MINUTES_KEY, (string) $value, $desc);
    }

    public function getSessionAbsoluteTimeoutHours(): int
    {
        $value = $this->settingsMetadataGateway->getInt(SettingKeys::SESSION_ABSOLUTE_TIMEOUT_HOURS_KEY);
        if ($value !== null && $this->isValidAbsoluteTimeout($value)) {
            return $value;
        }

        return self::ABSOLUTE_TIMEOUT_HOURS_FALLBACK;
    }

    public function setSessionAbsoluteTimeoutHours(?int $hours, ?string $description = null): bool
    {
        $value = $hours ?? self::ABSOLUTE_TIMEOUT_HOURS_FALLBACK;
        if (!$this->isValidAbsoluteTimeout($value)) {
            return false;
        }

        $desc = $description ?? 'setting.session_absolute_timeout_hours';
        return $this->settingsMetadataGateway->set(SettingKeys::SESSION_ABSOLUTE_TIMEOUT_HOURS_KEY, (string) $value, $desc);
    }

    public function getSessionIdleTimeoutSeconds(): int
    {
        return $this->getSessionIdleTimeoutMinutes() * 60;
    }

    public function getSessionAbsoluteTimeoutSeconds(): int
    {
        return $this->getSessionAbsoluteTimeoutHours() * 3600;
    }

    private function isValidIdleTimeout(int $minutes): bool
    {
        return $minutes >= self::IDLE_TIMEOUT_MINUTES_MIN && $minutes <= self::IDLE_TIMEOUT_MINUTES_MAX;
    }

    private function isValidAbsoluteTimeout(int $hours): bool
    {
        return $hours >= self::ABSOLUTE_TIMEOUT_HOURS_MIN && $hours <= self::ABSOLUTE_TIMEOUT_HOURS_MAX;
    }
}
