package org.dromara.system.controller.system;

import cn.dev33.satoken.annotation.SaIgnore;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.redis.utils.RedisUtils;
import org.dromara.system.service.ISysOssService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;

@SaIgnore
@RequiredArgsConstructor
@RestController
@RequestMapping("/resource/oss/endpoint")
public class SysOssEndpointController {

    private static final String VERIFY_OSS_KEY_PREFIX = "verify:oss:";

    private final ISysOssService ossService;

    @GetMapping("/public/{ossId}")
    public void downloadPublic(@PathVariable String ossId, HttpServletResponse response) throws IOException {
        if (StringUtils.isBlank(ossId) || !Boolean.TRUE.equals(RedisUtils.hasKey(VERIFY_OSS_KEY_PREFIX + ossId))) {
            response.setStatus(HttpServletResponse.SC_FORBIDDEN);
            return;
        }
        Long id;
        try {
            id = Long.valueOf(ossId);
        } catch (NumberFormatException e) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        try {
            ossService.download(id, response);
        } catch (Exception e) {
            response.setStatus(HttpServletResponse.SC_NOT_FOUND);
        }
    }
}

