package com.tashow.cloud.infra.controller.app.file;

import static com.tashow.cloud.common.pojo.CommonResult.success;

import cn.hutool.core.io.IoUtil;
import com.tashow.cloud.common.pojo.CommonResult;
import com.tashow.cloud.infra.controller.admin.file.vo.file.FileCreateReqVO;
import com.tashow.cloud.infra.controller.admin.file.vo.file.FilePresignedUrlRespVO;
import com.tashow.cloud.infra.controller.app.file.vo.AppFileUploadReqVO;
import com.tashow.cloud.infra.service.file.FileService;
import jakarta.annotation.Resource;
import jakarta.annotation.security.PermitAll;
import jakarta.validation.Valid;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/** 用户 App - 文件存储 */
@RestController
@RequestMapping("/infra/file")
@Validated
@Slf4j
public class AppFileController {

  @Resource private FileService fileService;

  /** 上传文件 */
  @PostMapping("/upload")
  @PermitAll
  public CommonResult<String> uploadFile(AppFileUploadReqVO uploadReqVO) throws Exception {
    MultipartFile file = uploadReqVO.getFile();
    String path = uploadReqVO.getPath();
    return success(
        fileService.createFile(
            file.getOriginalFilename(), path, IoUtil.readBytes(file.getInputStream())));
  }

  /** 获取文件预签名地址", description = "模式二：前端上传文件：用于前端直接上传七牛、阿里云 OSS 等文件存储器 */
  @GetMapping("/presigned-url")
  @PermitAll
  public CommonResult<FilePresignedUrlRespVO> getFilePresignedUrl(@RequestParam("path") String path)
      throws Exception {
    return success(fileService.getFilePresignedUrl(path));
  }

  /** 创建文件", description = "模式二：前端上传文件：配合 presigned-url 接口，记录上传了上传的文件 */
  @PostMapping("/create")
  @PermitAll
  public CommonResult<Long> createFile(@Valid @RequestBody FileCreateReqVO createReqVO) {
    return success(fileService.createFile(createReqVO));
  }
}
