package com.yd.oss.service.config;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.yd.oss.service.model.OssProvider;
import com.yd.oss.service.service.IOssProviderService;
import com.yd.oss.service.service.OssService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.annotation.PostConstruct;

@Configuration
@Slf4j
public class OssConfig {

    @Autowired
    private IOssProviderService ossProviderService;

    //默认的OSS提供商
    private OssProvider currentProvider;
    //默认存储桶名称
    private String defaultBucket;
    //默认服务端点
    private String defaultEndpoint;

    @PostConstruct
    public void init() {
        try {
            this.currentProvider = ossProviderService.getDefaultProvider();
            this.defaultBucket = currentProvider.getBucketName();
            this.defaultEndpoint = currentProvider.getEndpoint();
            log.info("默认OSS提供商初始化成功: {}", currentProvider.getName());
        } catch (Exception e) {
            log.error("默认OSS提供商初始化失败", e);
            throw new RuntimeException("默认OSS提供商初始化失败", e);
        }
    }

    @Bean
    @Primary
    public OSS ossClient() {
        return new OSSClientBuilder().build(
                currentProvider.getEndpoint(),
                currentProvider.getAccessKey(),
                currentProvider.getSecretKey()
        );
    }

//    @Bean
//    public OSS ossClient(OssService ossService) {
//        // 返回动态代理，每次调用都委托给 ossService.getOssClient()
//        return DynamicOssClientProxy.createProxy(ossService);
//    }

    @Bean
    public String defaultBucket() {
        return defaultBucket;
    }

    @Bean
    public String defaultEndpoint() {
        return defaultEndpoint;
    }

    @Bean
    public OssProvider currentProvider() {
        return currentProvider;
    }
}
