package com.mosquito.project.web;

import com.mosquito.project.config.AppConfig;
import com.mosquito.project.security.IntrospectionResponse;
import com.mosquito.project.security.UserIntrospectionService;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;

import java.util.Optional;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

class UserAuthInterceptorTest {

    @Test
    @DisplayName("缺少Authorization应拒绝")
    void shouldRejectRequest_whenMissingAuthorization() {
        UserIntrospectionService service = new UserIntrospectionService(new RestTemplateBuilder(), new AppConfig(), Optional.empty());
        UserAuthInterceptor interceptor = new UserAuthInterceptor(service);
        MockHttpServletRequest request = new MockHttpServletRequest();
        MockHttpServletResponse response = new MockHttpServletResponse();

        boolean result = interceptor.preHandle(request, response, new Object());

        assertFalse(result);
        assertEquals(401, response.getStatus());
    }

    @Test
    @DisplayName("空白Authorization应拒绝")
    void shouldRejectRequest_whenBlankAuthorization() {
        UserIntrospectionService service = new UserIntrospectionService(new RestTemplateBuilder(), new AppConfig(), Optional.empty());
        UserAuthInterceptor interceptor = new UserAuthInterceptor(service);
        MockHttpServletRequest request = new MockHttpServletRequest();
        request.addHeader("Authorization", "   "); // 空白
        MockHttpServletResponse response = new MockHttpServletResponse();

        boolean result = interceptor.preHandle(request, response, new Object());

        assertFalse(result);
        assertEquals(401, response.getStatus());
    }

    @Test
    @DisplayName("不活跃的token应拒绝")
    void shouldRejectRequest_whenTokenIsInactive() {
        // Given
        UserIntrospectionService service = mock(UserIntrospectionService.class);
        when(service.introspect(anyString())).thenReturn(IntrospectionResponse.inactive());

        UserAuthInterceptor interceptor = new UserAuthInterceptor(service);
        MockHttpServletRequest request = new MockHttpServletRequest();
        request.addHeader("Authorization", "Bearer expired-token");
        MockHttpServletResponse response = new MockHttpServletResponse();

        // When
        boolean result = interceptor.preHandle(request, response, new Object());

        // Then
        assertFalse(result);
        assertEquals(401, response.getStatus());
    }
}
