package com.yaoai.storage.service.impl;

import com.volcengine.tos.TOSV2;
import com.volcengine.tos.comm.common.ACLType;
import com.volcengine.tos.model.object.*;
import com.yaoai.common.exception.BizException;
import com.yaoai.common.exception.ErrorCode;
import com.yaoai.storage.config.TosProperties;
import com.yaoai.storage.service.TosService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;

@Slf4j
@Service
@RequiredArgsConstructor
public class TosServiceImpl implements TosService {

    private final TOSV2 tosClient;
    private final TosProperties properties;

    @Override
    public String upload(String key, InputStream content, long contentLength, String contentType) {
        ObjectMetaRequestOptions options = new ObjectMetaRequestOptions()
                .setContentType(contentType)
                .setAclType(ACLType.ACL_PUBLIC_READ);
        PutObjectInput input = new PutObjectInput()
                .setBucket(properties.getBucketName())
                .setKey(key)
                .setContent(content)
                .setContentLength(contentLength)
                .setOptions(options);
        tosClient.putObject(input);
        log.debug("TOS upload success: key={}, size={}", key, contentLength);
        return key;
    }

    @Override
    public void delete(String key) {
        tosClient.deleteObject(DeleteObjectInput.builder()
                .bucket(properties.getBucketName())
                .key(key)
                .build());
        log.debug("TOS delete success: key={}", key);
    }

    @Override
    public String readText(String key) {
        try {
            GetObjectV2Output output = tosClient.getObject(GetObjectV2Input.builder()
                    .bucket(properties.getBucketName())
                    .key(key)
                    .build());
            try (InputStream in = output.getContent()) {
                byte[] bytes = in.readAllBytes();
                log.debug("TOS readText: key={}, bytes={}", key, bytes.length);
                return new String(bytes, StandardCharsets.UTF_8);
            }
        } catch (IOException e) {
            log.error("TOS readText failed: key={}", key, e);
            throw new BizException(ErrorCode.INTERNAL_ERROR, "读取文件内容失败: " + e.getMessage());
        }
    }

    @Override
    public InputStream getInputStream(String key) throws IOException {
        GetObjectV2Output output = tosClient.getObject(GetObjectV2Input.builder()
                .bucket(properties.getBucketName())
                .key(key)
                .build());
        return output.getContent();
    }

    @Override
    public String presignedGetUrl(String key, long expiresSeconds) {
        return tosClient.preSignedURL(PreSignedURLInput.builder()
                .httpMethod("GET")
                .bucket(properties.getBucketName())
                .key(key)
                .expires(expiresSeconds)
                .build()).getSignedUrl();
    }

    @Override
    public String publicUrl(String key) {
        // bucket 须在火山引擎控制台设置为 public-read
        return String.format("https://%s.tos-%s.volces.com/%s",
                properties.getBucketName(), properties.getRegion(), key);
    }
}
