package com.gnx.telemedicine.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.Duration;
import java.util.HashMap;
import java.util.Map;

/**
 * Configuration for Redis caching.
 * Provides cache management for read-heavy operations.
 */
@Configuration
@EnableCaching
@ConditionalOnProperty(name = "spring.cache.type", havingValue = "redis", matchIfMissing = false)
@Slf4j
public class CacheConfig extends CachingConfigurerSupport {
    
    @Value("${spring.cache.redis.time-to-live:3600000}")
    private long defaultTtl;
    
    @Value("${spring.cache.redis.key-prefix:telemedicine:cache:}")
    private String keyPrefix;
    
    /**
     * Configure Redis cache manager with different TTLs for different caches.
     */
    @Bean
    public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
        RedisCacheConfiguration defaultConfig = RedisCacheConfiguration.defaultCacheConfig()
                .entryTtl(Duration.ofMillis(defaultTtl))
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(new GenericJackson2JsonRedisSerializer()))
                .disableCachingNullValues();
        
        // Define cache-specific configurations with different TTLs
        Map<String, RedisCacheConfiguration> cacheConfigurations = new HashMap<>();
        
        // User cache - 30 minutes
        cacheConfigurations.put("users", defaultConfig.entryTtl(Duration.ofMinutes(30)));
        cacheConfigurations.put("userByEmail", defaultConfig.entryTtl(Duration.ofMinutes(30)));
        cacheConfigurations.put("userProfile", defaultConfig.entryTtl(Duration.ofMinutes(30)));
        
        // Appointment cache - 15 minutes
        cacheConfigurations.put("appointments", defaultConfig.entryTtl(Duration.ofMinutes(15)));
        cacheConfigurations.put("appointmentsByPatient", defaultConfig.entryTtl(Duration.ofMinutes(15)));
        cacheConfigurations.put("appointmentsByDoctor", defaultConfig.entryTtl(Duration.ofMinutes(15)));
        cacheConfigurations.put("appointmentById", defaultConfig.entryTtl(Duration.ofMinutes(15)));
        
        // Doctor cache - 1 hour
        cacheConfigurations.put("doctors", defaultConfig.entryTtl(Duration.ofHours(1)));
        cacheConfigurations.put("doctorById", defaultConfig.entryTtl(Duration.ofHours(1)));
        cacheConfigurations.put("doctorByUserId", defaultConfig.entryTtl(Duration.ofHours(1)));
        cacheConfigurations.put("doctorAvailability", defaultConfig.entryTtl(Duration.ofMinutes(30)));
        
        // Patient cache - 1 hour
        cacheConfigurations.put("patients", defaultConfig.entryTtl(Duration.ofHours(1)));
        cacheConfigurations.put("patientById", defaultConfig.entryTtl(Duration.ofHours(1)));
        cacheConfigurations.put("patientByUserId", defaultConfig.entryTtl(Duration.ofHours(1)));
        
        // Admin stats cache - 5 minutes
        cacheConfigurations.put("adminStats", defaultConfig.entryTtl(Duration.ofMinutes(5)));
        
        // Prescription cache - 30 minutes
        cacheConfigurations.put("prescriptions", defaultConfig.entryTtl(Duration.ofMinutes(30)));
        cacheConfigurations.put("prescriptionsByPatient", defaultConfig.entryTtl(Duration.ofMinutes(30)));
        cacheConfigurations.put("prescriptionsByDoctor", defaultConfig.entryTtl(Duration.ofMinutes(30)));
        
        // Medical records cache - 30 minutes
        cacheConfigurations.put("medicalRecords", defaultConfig.entryTtl(Duration.ofMinutes(30)));
        cacheConfigurations.put("medicalRecordsByPatient", defaultConfig.entryTtl(Duration.ofMinutes(30)));
        
        // Vital signs cache - 15 minutes
        cacheConfigurations.put("vitalSigns", defaultConfig.entryTtl(Duration.ofMinutes(15)));
        cacheConfigurations.put("vitalSignsByPatient", defaultConfig.entryTtl(Duration.ofMinutes(15)));
        
        // Lab results cache - 30 minutes
        cacheConfigurations.put("labResults", defaultConfig.entryTtl(Duration.ofMinutes(30)));
        cacheConfigurations.put("labResultsByPatient", defaultConfig.entryTtl(Duration.ofMinutes(30)));
        
        RedisCacheManager cacheManager = RedisCacheManager.builder(connectionFactory)
                .cacheDefaults(defaultConfig)
                .withInitialCacheConfigurations(cacheConfigurations)
                .transactionAware()
                .build();
        
        log.info("Redis cache manager configured with {} cache configurations", cacheConfigurations.size());
        return cacheManager;
    }
    
    /**
     * Configure Redis template for manual cache operations.
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }
}

