package cn.reghao.oss.web.app.controller;

import cn.reghao.jutil.jdk.result.WebResult;
import cn.reghao.oss.api.dto.DownloadUrl;
import cn.reghao.oss.api.dto.ObjectChannel;
import cn.reghao.oss.api.dto.ObjectInfo;
import cn.reghao.oss.api.dto.ServerInfo;
import cn.reghao.oss.web.app.service.OssService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author reghao
 * @date 2024-02-23 09:27:36
 */
@Api(tags = "OSS 接口")
@RestController
@RequestMapping("/api/oss")
public class OssController {
    private final OssService ossService;

    public OssController(OssService ossService) {
        this.ossService = ossService;
    }

    @ApiOperation(value = "获取 oss-store 节点")
    @GetMapping(value = "/server/info", produces = MediaType.APPLICATION_JSON_VALUE)
    public String getServerInfo(@RequestParam("channelId") int channelId) throws Exception {
        ServerInfo serverInfo = ossService.getServerInfo(channelId);
        return WebResult.success(serverInfo);
    }

    @ApiOperation(value = "获取所有的 UploadChannel")
    @GetMapping(value = "/channels", produces = MediaType.APPLICATION_JSON_VALUE)
    public String getChannels(@RequestParam("nodeAddr") String nodeAddr) {
        List<ObjectChannel> list = ossService.getObjectChannels(nodeAddr);
        return WebResult.success(list);
    }

    @ApiOperation(value = "获取某个 UploadChannel")
    @GetMapping(value = "/channel", produces = MediaType.APPLICATION_JSON_VALUE)
    public String getChannel(@RequestParam("nodeAddr") String nodeAddr, @RequestParam("channelId") int channelId) {
        ObjectChannel objectChannel = ossService.getObjectChannel(nodeAddr, channelId);
        return WebResult.success(objectChannel);
    }

    @ApiOperation(value = "获取对象信息")
    @GetMapping(value = "/object/info", produces = MediaType.APPLICATION_JSON_VALUE)
    public String getObjectInfo(@RequestParam("objectId") String objectId) {
        ObjectInfo objectInfo = ossService.getObjectInfo(objectId);
        return WebResult.success(objectInfo);
    }

    @ApiOperation(value = "获取对象 url")
    @GetMapping(value = "/object/url", produces = MediaType.APPLICATION_JSON_VALUE)
    public String getObjectUrl(@RequestParam("objectId") String objectId,
                               @RequestParam("channelId") Integer channelId,
                               @RequestParam("userId") Long userId) {
        DownloadUrl downloadUrl = ossService.getDownloadUrl(objectId, channelId, userId);
        return WebResult.success(downloadUrl);
    }
}
