package com.ruoyi.framework.web.service;

import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertNull;

import java.nio.charset.StandardCharsets;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruoyi.common.core.domain.entity.SysRole;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.domain.model.LoginUser;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

@DisplayName("LoginUserRedisStore Jackson 序列化")
class LoginUserRedisStoreJacksonTest
{
    private static final String LEGACY_FASTJSON =
            "{\"@type\":\"com.ruoyi.common.core.domain.model.LoginUser\",\"deptId\":103,"
                    + "\"permissions\":[\"*:*:*\"],\"token\":\"t1\","
                    + "\"user\":{\"userId\":1,\"userName\":\"admin\","
                    + "\"roles\":[{\"roleId\":1,\"roleKey\":\"admin\",\"flag\":false,"
                    + "\"deptCheckStrictly\":false,\"menuCheckStrictly\":false}]},"
                    + "\"userId\":1,\"username\":\"admin\"}";

    @Test
    @DisplayName("Jackson 读写含 roles 的 LoginUser")
    void jacksonRoundTrip() throws Exception
    {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        SysRole role = new SysRole();
        role.setRoleId(1L);
        role.setRoleKey("admin");
        role.setFlag(false);
        SysUser user = new SysUser(1L);
        user.setUserName("admin");
        user.setRoles(java.util.Collections.singletonList(role));
        LoginUser loginUser = new LoginUser(1L, 103L, user, java.util.Collections.singleton("*:*:*"));
        loginUser.setToken("t1");

        byte[] bytes = mapper.writeValueAsBytes(loginUser);
        LoginUser restored = mapper.readValue(bytes, LoginUser.class);
        assertNotNull(restored.getUser());
        assertEquals("admin", restored.getUser().getUserName());
        assertEquals(1, restored.getUser().getRoles().size());
    }

    @Test
    @DisplayName("Legacy FastJSON 含 flag:false 可被 Jackson 忽略未知字段策略兼容读取")
    void jacksonIgnoresUnknownFromPlainJson() throws Exception
    {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        LoginUser loginUser = mapper.readValue(LEGACY_FASTJSON.getBytes(StandardCharsets.UTF_8), LoginUser.class);
        assertNotNull(loginUser);
        assertEquals("admin", loginUser.getUser().getUserName());
    }
}
