package com.magistr.app.config.auth;

import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThatCode;
import static org.assertj.core.api.Assertions.assertThatThrownBy;

class JwtPropertiesTest {

    @Test
    void rejectsMissingSecret() {
        JwtProperties properties = new JwtProperties();

        assertThatThrownBy(properties::secretBytes)
                .isInstanceOf(IllegalStateException.class)
                .hasMessage("JWT_SECRET обязателен и не может быть пустым");
    }

    @Test
    void rejectsShortSecret() {
        JwtProperties properties = properties("short-value", true);

        assertThatThrownBy(properties::secretBytes)
                .isInstanceOf(IllegalStateException.class)
                .hasMessage("JWT_SECRET должен быть не короче 32 байт");
    }

    @Test
    void rejectsPlaceholderSecret() {
        String placeholder = String.join("-", "replace", "with", "production", "value") + "x".repeat(32);
        JwtProperties properties = properties(placeholder, true);

        assertThatThrownBy(properties::secretBytes)
                .isInstanceOf(IllegalStateException.class)
                .hasMessage("JWT_SECRET содержит известное небезопасное или шаблонное значение");
    }

    @Test
    void rejectsInsecureRefreshCookieInProduction() {
        JwtProperties properties = properties(testSecret(), false);

        assertThatThrownBy(() -> properties.validateForEnvironment(true))
                .isInstanceOf(IllegalStateException.class)
                .hasMessage("В production-профиле JWT_REFRESH_COOKIE_SECURE должен иметь значение true");
    }

    @Test
    void allowsInsecureRefreshCookieOutsideProduction() {
        JwtProperties properties = properties(testSecret(), false);

        assertThatCode(() -> properties.validateForEnvironment(false)).doesNotThrowAnyException();
    }

    @Test
    void acceptsSecureProductionConfiguration() {
        JwtProperties properties = properties(testSecret(), true);

        assertThatCode(() -> properties.validateForEnvironment(true)).doesNotThrowAnyException();
    }

    private JwtProperties properties(String secret, boolean secureCookie) {
        JwtProperties properties = new JwtProperties();
        properties.setSecret(secret);
        properties.setRefreshCookieSecure(secureCookie);
        return properties;
    }

    private String testSecret() {
        return "A1b2C3d4".repeat(6);
    }
}
