package com.bizzan.bitrade.service;

import com.amazonaws.auth.AWSStaticCredentialsProvider;
import com.amazonaws.auth.BasicAWSCredentials;
import com.amazonaws.client.builder.AwsClientBuilder;
import com.amazonaws.services.s3.AmazonS3;
import com.amazonaws.services.s3.AmazonS3ClientBuilder;
import com.bizzan.bitrade.config.S3Config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.io.InputStream;

@Slf4j
@Service
public class S3Service {

    @Autowired
    private S3Config s3Config;

    private AmazonS3 s3Client;

    @PostConstruct
    public void init() {
        if (s3Config.getAccessKeyId() == null || s3Config.getAccessKeyId().isEmpty()
                || s3Config.getAccessKeyId().startsWith("@")) {
            log.warn("S3 config not present (accessKeyId is empty or unresolved), S3Service disabled");
            return;
        }
        BasicAWSCredentials credentials = new BasicAWSCredentials(
                s3Config.getAccessKeyId(), s3Config.getAccessKeySecret());
        if (s3Config.getEndpoint() != null && !s3Config.getEndpoint().isEmpty()) {
            this.s3Client = AmazonS3ClientBuilder.standard()
                    .withCredentials(new AWSStaticCredentialsProvider(credentials))
                    .withEndpointConfiguration(new AwsClientBuilder.EndpointConfiguration(
                            s3Config.getEndpoint(), s3Config.getRegion()))
                    .build();
        } else {
            this.s3Client = AmazonS3ClientBuilder.standard()
                    .withCredentials(new AWSStaticCredentialsProvider(credentials))
                    .withRegion(s3Config.getRegion())
                    .build();
        }
        log.info("S3 client initialized - bucket={}, region={}", s3Config.getBucketName(), s3Config.getRegion());
    }

    public String upload(String key, InputStream inputStream) {
        if (s3Client == null) {
            log.error("S3Service is not initialized, cannot upload key={}", key);
            throw new IllegalStateException("S3Service is not available");
        }
        s3Client.putObject(s3Config.getBucketName(), key, inputStream, null);
        String url = s3Config.toUrl(key);
        log.info("S3 upload success - key={}", key);
        return url;
    }
}
