package com.starry.admin.modules.common.controller;

import cn.hutool.core.util.StrUtil;
import com.starry.admin.common.exception.CustomException;
import com.starry.admin.common.oss.service.IOssFileService;
import com.starry.admin.utils.SecurityUtils;
import com.starry.common.result.R;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import java.io.IOException;
import javax.annotation.Resource;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

/**
 * 后台通用能力接口
 */
@Api(tags = "后台通用接口", description = "提供后台常用的公共能力，例如文件上传")
@RestController
@RequestMapping("/common")
public class CommonController {

    @Resource
    private IOssFileService ossFileService;

    @ApiOperation(value = "上传文件", notes = "上传文件到 OSS 并返回访问地址")
    @PostMapping("/upload")
    public R upload(@ApiParam(value = "上传文件", required = true) @RequestParam("file") MultipartFile file)
            throws IOException {
        if (file == null || file.isEmpty()) {
            throw new CustomException("上传文件不能为空");
        }
        String tenantId = SecurityUtils.getTenantId();
        if (StrUtil.isBlank(tenantId)) {
            throw new CustomException("租户信息缺失，请重新登录");
        }
        String fileUrl = ossFileService.upload(file.getInputStream(), tenantId, file.getOriginalFilename());
        return R.ok(fileUrl);
    }
}
