package com.magistr.app.config.auth;

import jakarta.annotation.PostConstruct;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.time.Duration;

@Component
@ConfigurationProperties(prefix = "app.login-security")
public class LoginSecurityProperties {

    private int maxFailures = 5;
    private Duration attemptWindow = Duration.ofMinutes(15);
    private Duration baseBlockDuration = Duration.ofMinutes(1);
    private Duration maxBlockDuration = Duration.ofMinutes(15);

    @PostConstruct
    void validate() {
        if (maxFailures < 2 || maxFailures > 100) {
            throw new IllegalStateException("LOGIN_RATE_MAX_FAILURES должен быть от 2 до 100");
        }
        requirePositive(attemptWindow, "Окно учёта попыток входа");
        requirePositive(baseBlockDuration, "Начальный срок блокировки входа");
        requirePositive(maxBlockDuration, "Максимальный срок блокировки входа");
        if (maxBlockDuration.compareTo(baseBlockDuration) < 0) {
            throw new IllegalStateException(
                    "Максимальный срок блокировки входа не может быть меньше начального"
            );
        }
    }

    private void requirePositive(Duration duration, String fieldName) {
        if (duration == null || duration.isZero() || duration.isNegative()) {
            throw new IllegalStateException(fieldName + " должен быть положительным");
        }
    }

    public int getMaxFailures() {
        return maxFailures;
    }

    public void setMaxFailures(int maxFailures) {
        this.maxFailures = maxFailures;
    }

    public Duration getAttemptWindow() {
        return attemptWindow;
    }

    public void setAttemptWindow(Duration attemptWindow) {
        this.attemptWindow = attemptWindow;
    }

    public Duration getBaseBlockDuration() {
        return baseBlockDuration;
    }

    public void setBaseBlockDuration(Duration baseBlockDuration) {
        this.baseBlockDuration = baseBlockDuration;
    }

    public Duration getMaxBlockDuration() {
        return maxBlockDuration;
    }

    public void setMaxBlockDuration(Duration maxBlockDuration) {
        this.maxBlockDuration = maxBlockDuration;
    }
}
