package xtools.boot.storage.s3.service.impl;

import jakarta.annotation.Resource;
import jakarta.validation.constraints.NotNull;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import software.amazon.awssdk.services.s3.S3Client;
import xtools.base.config.BaseParams;
import xtools.boot.storage.base.service.StorageService;
import xtools.extend.S3Utils;

import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.Set;

/**
 * <p>Title : StorageServiceS3Impl</p>
 * <p>Description : StorageServiceS3Impl</p>
 * <p>DevelopTools : Idea_x64_v2026.1</p>
 * <p>DevelopSystem : macOS Sequoia 15.7.5</p>
 * <p>Company : org.xujun</p>
 *
 * @author : XuJun
 * @version : 5.0.0
 * @date : 2026/3/14 07:35
 */
@Slf4j
@RequiredArgsConstructor
public class StorageServiceS3Impl implements StorageService, BaseParams {

    /**
     * 桶集合
     */
    private final static Set<String> BUCKET_SET = new HashSet<>();

    @Resource
    private S3Client s3Client;

    /**
     * 是否存在文件
     *
     * @param bucket   桶
     * @param fileName 文件名
     * @return true or false
     */
    @Override
    public boolean exists(
            @NotNull String bucket,
            @NotNull String fileName
    ) {
        initBucket(bucket);
        return S3Utils.exists(s3Client, bucket, fileName);
    }

    /**
     * 保存文件
     *
     * @param bucket        桶
     * @param fileName      文件名
     * @param inputStream   输入流
     * @param contentLength 文件长度
     */
    @Override
    public void save(
            @NotNull String bucket,
            @NotNull String fileName,
            @NotNull InputStream inputStream,
            long contentLength
    ) {
        initBucket(bucket);
        S3Utils.upload(s3Client, bucket, fileName, inputStream, contentLength);
    }

    /**
     * 获取文件
     *
     * @param bucket       桶
     * @param fileName     文件名
     * @param outputStream 输出流
     */
    @Override
    public void get(
            @NotNull String bucket,
            @NotNull String fileName,
            @NotNull OutputStream outputStream
    ) {
        S3Utils.download(s3Client, bucket, fileName, outputStream);
    }

    /**
     * 删除文件
     *
     * @param bucket   桶
     * @param fileName 文件名
     */
    @Override
    public void del(
            @NotNull String bucket,
            @NotNull String fileName
    ) {
        S3Utils.delete(s3Client, bucket, fileName);
    }

    /**
     * 初始化桶
     *
     * @param bucket 桶
     */
    private void initBucket(String bucket) {
        if (BUCKET_SET.contains(bucket)) {
            return;
        }
        try {
            S3Utils.createBucket(s3Client, bucket);
        } catch (Exception e) {
            log.info("文件桶已存在", e);
        }
        BUCKET_SET.add(bucket);
    }
}
