package com.xly.erp.common.security;

import com.xly.erp.common.exception.BizException;
import org.junit.jupiter.api.Test;

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

class JwtUtilTest {

    private static final String SECRET = "f8d4be76bff13bf32fa33ca0b14a4b152ad01ca5719f57df18ec4ecf2370b235";

    private final JwtUtil jwtUtil = new JwtUtil(SECRET);

    @Test
    void signAndParse_roundTrip() {
        String token = jwtUtil.sign("ALICE001");
        assertThat(token).isNotBlank();
        assertThat(jwtUtil.parse(token)).isEqualTo("ALICE001");
    }

    @Test
    void parseTamperedToken_throwsBizException20001() {
        String token = jwtUtil.sign("ALICE001");
        String tampered = token.substring(0, token.length() - 4) + "XXXX";
        assertThatThrownBy(() -> jwtUtil.parse(tampered))
                .isInstanceOf(BizException.class)
                .hasFieldOrPropertyWithValue("code", 20001);
    }

    @Test
    void parseGarbageToken_throwsBizException20001() {
        assertThatThrownBy(() -> jwtUtil.parse("not.a.real.jwt"))
                .isInstanceOf(BizException.class)
                .hasFieldOrPropertyWithValue("code", 20001);
    }

    @Test
    void signRefresh_signsValidLongerLivedToken() {
        String accessToken = jwtUtil.sign("U1");
        String refreshToken = jwtUtil.signRefresh("U1");
        assertThat(jwtUtil.parse(accessToken)).isEqualTo("U1");
        assertThat(jwtUtil.parse(refreshToken)).isEqualTo("U1");
        assertThat(refreshToken).isNotEqualTo(accessToken);
    }
}
