package com.ruoyi.framework.config;

import static org.junit.jupiter.api.Assertions.assertDoesNotThrow;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertNotNull;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.util.Collections;
import java.util.List;

import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;

import com.alibaba.fastjson2.JSONArray;
import com.ruoyi.common.core.domain.entity.SysDictData;

/**
 * 复现 sys_normal_disable 字典 Redis 缓存 Fastjson2 反序列化失败。
 */
@DisplayName("SysDictData Redis 序列化")
class SysDictDataRedisSerializerTest
{
    @Test
    @DisplayName("Object.class 序列化字典列表不含 default 布尔字段")
    void dictListRoundTripAsObjectClass()
    {
        SysDictData row = new SysDictData();
        row.setDictCode(1L);
        row.setDictSort(1L);
        row.setDictLabel("正常");
        row.setDictValue("0");
        row.setDictType("sys_normal_disable");
        row.setListClass("primary");
        row.setIsDefault("Y");
        row.setStatus("0");
        List<SysDictData> list = Collections.singletonList(row);

        FastJson2JsonRedisSerializer<Object> serializer = new FastJson2JsonRedisSerializer<>(Object.class);
        byte[] bytes = serializer.serialize(list);
        String json = new String(bytes, FastJson2JsonRedisSerializer.DEFAULT_CHARSET);
        assertFalse(json.contains("\"default\":"), () -> "不应序列化 getDefault() 为 default 字段：" + json);

        Object raw = assertDoesNotThrow(() -> serializer.deserialize(bytes));
        assertNotNull(raw);
        JSONArray array = (JSONArray) raw;
        assertTrue(array.size() > 0);
        SysDictData restored = array.getObject(0, SysDictData.class);
        assertNotNull(restored);
        assertTrue("正常".equals(restored.getDictLabel()));
    }

    @Test
    @DisplayName("兼容含 legacy default:false 的历史缓存")
    void deserializeLegacyDictCacheWithDefaultField()
    {
        String legacyJson =
                "[{\"@type\":\"com.ruoyi.common.core.domain.entity.SysDictData\",\"dictCode\":1,"
                        + "\"dictLabel\":\"正常\",\"dictValue\":\"0\",\"dictType\":\"sys_normal_disable\","
                        + "\"isDefault\":\"Y\",\"default\":false,\"listClass\":\"primary\",\"status\":\"0\"}]";
        FastJson2JsonRedisSerializer<Object> serializer = new FastJson2JsonRedisSerializer<>(Object.class);
        Object raw = assertDoesNotThrow(
                () -> serializer.deserialize(legacyJson.getBytes(FastJson2JsonRedisSerializer.DEFAULT_CHARSET)));
        assertNotNull(raw);
    }
}
