package com.ruoyi.config;

import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.core.rolling.RollingFileAppender;
import org.junit.jupiter.api.Test;
import org.slf4j.LoggerFactory;
import org.springframework.boot.logging.LogFile;
import org.springframework.boot.logging.LoggingInitializationContext;
import org.springframework.boot.logging.logback.LogbackLoggingSystem;
import org.springframework.core.env.MapPropertySource;
import org.springframework.core.env.StandardEnvironment;

import java.util.Map;

import static org.assertj.core.api.Assertions.assertThat;

class LogbackConfigurationTest {

    @Test
    void shouldUseLogPathFromApplicationConfiguration() {
        StandardEnvironment environment = new StandardEnvironment();
        environment.getPropertySources().addFirst(new MapPropertySource("test", Map.of(
            "logging.file.path", "/tmp/ccdi-logback-test"
        )));

        LogbackLoggingSystem loggingSystem = new LogbackLoggingSystem(getClass().getClassLoader());
        try {
            loggingSystem.beforeInitialize();
            loggingSystem.initialize(
                new LoggingInitializationContext(environment),
                "classpath:logback-spring.xml",
                LogFile.get(environment)
            );

            LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory();
            Logger rootLogger = context.getLogger(Logger.ROOT_LOGGER_NAME);
            RollingFileAppender<?> infoAppender = (RollingFileAppender<?>) rootLogger.getAppender("file_info");
            RollingFileAppender<?> errorAppender = (RollingFileAppender<?>) rootLogger.getAppender("file_error");
            RollingFileAppender<?> userAppender = (RollingFileAppender<?>) context.getLogger("sys-user").getAppender("sys-user");

            assertThat(infoAppender.getFile()).isEqualTo("/tmp/ccdi-logback-test/sys-info.log");
            assertThat(errorAppender.getFile()).isEqualTo("/tmp/ccdi-logback-test/sys-error.log");
            assertThat(userAppender.getFile()).isEqualTo("/tmp/ccdi-logback-test/sys-user.log");
        } finally {
            loggingSystem.cleanUp();
            ((LoggerContext) LoggerFactory.getILoggerFactory()).reset();
        }
    }
}
