package com.nanri.aiimage.modules.file.service.oss;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.nanri.aiimage.config.OssProperties;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.io.File;
import java.net.URL;
import java.util.Date;
import java.util.UUID;

@Service
@RequiredArgsConstructor
public class OssStorageService {

    private final OssProperties ossProperties;

    public String uploadResultFile(File file, String moduleType) {
        String objectKey = String.format("result/%s/%s/%s", moduleType.toLowerCase(), UUID.randomUUID(), file.getName());
        OSS ossClient = new OSSClientBuilder().build(
                "https://" + ossProperties.getEndpoint(),
                ossProperties.getAccessKeyId(),
                ossProperties.getAccessKeySecret()
        );
        try {
            ossClient.putObject(ossProperties.getBucket(), objectKey, file);
            return objectKey;
        } finally {
            ossClient.shutdown();
        }
    }

    public String generateDownloadUrl(String objectKey) {
        OSS ossClient = new OSSClientBuilder().build(
                "https://" + ossProperties.getEndpoint(),
                ossProperties.getAccessKeyId(),
                ossProperties.getAccessKeySecret()
        );
        try {
            Date expiration = new Date(System.currentTimeMillis() + 3600_000L);
            URL url = ossClient.generatePresignedUrl(ossProperties.getBucket(), objectKey, expiration);
            return url.toString();
        } finally {
            ossClient.shutdown();
        }
    }
}
