package com.ruoyi.web.modules.openstats.filter;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.io.IOException;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
import com.ruoyi.web.modules.openstats.constant.OpenStatsConstants;
import com.ruoyi.web.modules.openstats.support.OpenStatsTokenSupport;

@ExtendWith(MockitoExtension.class)
class OpenStatsTokenFilterTest
{
    @Mock
    private OpenStatsTokenSupport tokenSupport;

    @Mock
    private FilterChain filterChain;

    @InjectMocks
    private OpenStatsTokenFilter filter;

    private MockHttpServletRequest request;

    private MockHttpServletResponse response;

    @BeforeEach
    void setUp()
    {
        request = new MockHttpServletRequest();
        response = new MockHttpServletResponse();
    }

    @Test
    void doFilter_missingTokenReturns401() throws Exception
    {
        when(tokenSupport.isValidToken(null)).thenReturn(false);

        filter.doFilterInternal(request, response, filterChain);

        assertEquals(401, response.getStatus());
        verify(filterChain, never()).doFilter(any(), any());
    }

    @Test
    void doFilter_invalidTokenReturns401() throws Exception
    {
        request.addHeader(OpenStatsConstants.TOKEN_HEADER, "bad-token");
        when(tokenSupport.isValidToken("bad-token")).thenReturn(false);

        filter.doFilterInternal(request, response, filterChain);

        assertEquals(401, response.getStatus());
        verify(filterChain, never()).doFilter(any(), any());
    }

    @Test
    void doFilter_validTokenContinuesChain() throws IOException, ServletException
    {
        request.addHeader(OpenStatsConstants.TOKEN_HEADER, "good-token");
        when(tokenSupport.isValidToken("good-token")).thenReturn(true);

        filter.doFilterInternal(request, response, filterChain);

        verify(filterChain).doFilter(request, response);
    }
}
