package cn.meowrain.aioj.backend.fileservice.config;

import cn.meowrain.aioj.backend.fileservice.storage.FileStorageStrategy;
import cn.meowrain.aioj.backend.fileservice.storage.impl.CosFileStorageStrategy;
import cn.meowrain.aioj.backend.fileservice.storage.impl.LocalFileStorageStrategy;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

/**
 * 文件存储配置类
 * 根据配置自动选择存储策略
 *
 * @author meowrain
 * @since 2026-01-10
 */
@Slf4j
@Configuration
@RequiredArgsConstructor
public class FileStorageConfig {

    private final LocalFileStorageStrategy localFileStorageStrategy;
    private final FileConfigurationProperties fileConfigurationProperties;
    private final ApplicationContext applicationContext;

    /**
     * 配置文件存储策略
     * 优先使用腾讯云COS，如果未启用则使用本地存储
     */
    @Bean
    @Primary
    public FileStorageStrategy fileStorageStrategy() {
        if (fileConfigurationProperties.isUseCloud()) {
            try {
                CosFileStorageStrategy cosStrategy = applicationContext.getBean(CosFileStorageStrategy.class);
                log.info("使用腾讯云COS文件存储策略");
                return cosStrategy;
            } catch (Exception e) {
                log.warn("腾讯云COS未配置，回退到本地文件存储策略");
                return localFileStorageStrategy;
            }
        } else {
            log.info("使用本地文件存储策略");
            return localFileStorageStrategy;
        }
    }
}
