package com.xunhong.erp.turbo.infra.infrastructure.gateway;

import cn.hutool.core.date.LocalDateTimeUtil;
import com.xunhong.erp.turbo.base.utils.FileUploadUtil;
import com.xunhong.erp.turbo.file.FileService;
import com.xunhong.erp.turbo.file.config.OssProperties;
import com.xunhong.erp.turbo.infra.domain.entity.Credentials;
import com.xunhong.erp.turbo.infra.domain.gateway.OssGateway;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Repository;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;


/**
 * @author shenyifei
 */
@Repository
@RequiredArgsConstructor
public class OssGatewayImpl implements OssGateway {

	private final OssProperties properties;

	private final FileService fileService;

	private final OssConvert ossConvert;

	@Override
	public Credentials getOssToken() {
		Credentials credentials = ossConvert.toCredentials(fileService.getOssToken());
		credentials.setDomain(properties.getDomain());
		credentials.setBucket(properties.getBucket());
		credentials.setRegion(properties.getRegion());
		return credentials;
	}

	@Override
	public String upload(MultipartFile file) {
		// 使用FileUploadUtil安全处理文件名
		String objectName = FileUploadUtil.generateObjectName(file);

		try {
			fileService.upload(objectName, file.getInputStream());

			return objectName;
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}

	@Override
	public String upload(File file) {
		String objectName = "uploads/" + LocalDateTimeUtil.format(LocalDateTimeUtil.now(), "yyMM/dd") + "/" + file.getName();

		fileService.upload(objectName, file);

		return objectName;
	}
}
