package dev.ksan.etfoglasiserver.service;

import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.junit.jupiter.MockitoExtension;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.TestPropertySource;

import java.lang.reflect.Field;

import static org.assertj.core.api.AssertionsForClassTypes.assertThat;
import static org.assertj.core.api.AssertionsForClassTypes.assertThatThrownBy;

@ExtendWith(MockitoExtension.class)
class JWTServiceTest {

    private JWTService jwtService;

    private static final String TEST_SECRET =
            "dGVzdHNlY3JldGtleXRoYXRpc2xvbmdlbm91Z2hmb3JibWFjc2hhMjU2dGVzdGtleQ==";

    @BeforeEach
    void setUp() throws Exception {
        jwtService = new JWTService();
        Field secret = JWTService.class.getDeclaredField("secretKey");
        secret.setAccessible(true);
        secret.set(jwtService, TEST_SECRET);
    }

    @Test
    void generateToken_extractEmail_returnsCorrectEmail() {
        String token = jwtService.generateToken("alice@example.com");
        assertThat(jwtService.extractEmail(token)).isEqualTo("alice@example.com");
    }

    @Test
    void validateToken_correctUser_returnsTrue() {
        String token = jwtService.generateToken("alice@example.com");
        assertThat(jwtService.validateToken(token, userDetails("alice@example.com"))).isTrue();
    }

    @Test
    void validateToken_differentUser_returnsFalse() {
        String token = jwtService.generateToken("alice@example.com");
        assertThat(jwtService.validateToken(token, userDetails("bob@example.com"))).isFalse();
    }

    @Test
    void validateToken_tamperedToken_throwsException() {
        String token = jwtService.generateToken("alice@example.com");
        String tampered = token.substring(0, token.length() - 4) + "XXXX";
        assertThatThrownBy(() -> jwtService.validateToken(tampered, userDetails("alice@example.com")))
                .isInstanceOf(Exception.class);
    }

    private org.springframework.security.core.userdetails.UserDetails userDetails(String email) {
        return org.springframework.security.core.userdetails.User
                .withUsername(email).password("x").roles("USER").build();
    }
}