package cn.nianxx.thhotel.integrations.storage.aliyunoss.service.impl;

import cn.nianxx.thhotel.integrations.storage.aliyunoss.common.request.ObjectStoragePutRequest;
import cn.nianxx.thhotel.integrations.storage.aliyunoss.common.result.ObjectStoragePutResult;
import cn.nianxx.thhotel.integrations.storage.aliyunoss.service.ObjectStorageService;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.model.ObjectMetadata;
import java.io.ByteArrayInputStream;
import org.springframework.stereotype.Service;

/**
 * 阿里云 OSS 上传适配实现。负责 SDK 调用和 URL 拼接，业务层不感知 OSS SDK。
 */
@Service
public class AliyunOssObjectStorageServiceImpl implements ObjectStorageService {

    private final AliyunOssProperties properties;

    /**
     * 注入阿里云 OSS 配置。
     */
    public AliyunOssObjectStorageServiceImpl(AliyunOssProperties properties) {
        this.properties = properties;
    }

    /**
     * 上传对象到阿里云 OSS；配置缺失时失败，避免误以为本地 mock 已生效。
     */
    @Override
    public ObjectStoragePutResult putObject(ObjectStoragePutRequest request) {
        validateProperties();
        if (request == null || request.objectKey() == null || request.objectKey().isBlank()) {
            throw new ObjectStorageException("OSS object key 不能为空。");
        }
        byte[] content = request.content() == null ? new byte[0] : request.content();
        ObjectMetadata metadata = new ObjectMetadata();
        metadata.setContentLength(content.length);
        if (request.contentType() != null && !request.contentType().isBlank()) {
            metadata.setContentType(request.contentType());
        }
        OSS ossClient = new OSSClientBuilder().build(
                properties.getEndpoint(),
                properties.getAccessKeyId(),
                properties.getAccessKeySecret());
        try {
            ossClient.putObject(
                    properties.getBucket(),
                    request.objectKey(),
                    new ByteArrayInputStream(content),
                    metadata);
            return new ObjectStoragePutResult(
                    request.objectKey(),
                    publicUrl(request.objectKey()),
                    request.contentType(),
                    (long) content.length);
        } catch (Exception exception) {
            throw new ObjectStorageException("阿里云 OSS 上传失败。", exception);
        } finally {
            ossClient.shutdown();
        }
    }

    /**
     * 校验 OSS 必要配置，错误消息不包含任何 Secret。
     */
    private void validateProperties() {
        if (blank(properties.getEndpoint()) || blank(properties.getBucket())
                || blank(properties.getAccessKeyId()) || blank(properties.getAccessKeySecret())
                || blank(properties.getPublicBaseUrl())) {
            throw new ObjectStorageException("阿里云 OSS 配置不完整。");
        }
    }

    /**
     * 根据公开访问基础 URL 拼接对象 URL。
     */
    private String publicUrl(String objectKey) {
        String baseUrl = properties.getPublicBaseUrl();
        String normalizedBase = baseUrl.endsWith("/") ? baseUrl.substring(0, baseUrl.length() - 1) : baseUrl;
        return normalizedBase + "/" + objectKey;
    }

    /**
     * 判断字符串是否为空白。
     */
    private boolean blank(String value) {
        return value == null || value.isBlank();
    }
}
