package com.seer.teach.filter.auth.redis;

import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.type.TypeFactory;
import com.seer.teach.filter.auth.Permission;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.ReactiveRedisConnectionFactory;
import org.springframework.data.redis.core.ReactiveRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.util.List;

@Configuration
public class RedisConfig {

    @Bean
    public ReactiveRedisTemplate<String, List<Permission>> permissionRedisTemplate(
            ReactiveRedisConnectionFactory factory) {

        JavaType javaType = TypeFactory.defaultInstance().constructParametricType(
                List.class,
                Permission.class
        );

        Jackson2JsonRedisSerializer<List<Permission>> valueSerializer =
                new Jackson2JsonRedisSerializer<>(javaType);

        RedisSerializationContext<String, List<Permission>> context =
                RedisSerializationContext.<String, List<Permission>>newSerializationContext()
                        .key(new StringRedisSerializer())
                        .value(valueSerializer)
                        .hashKey(new StringRedisSerializer())
                        .hashValue(valueSerializer)
                        .build();

        return new ReactiveRedisTemplate<>(factory, context);
    }
}
