package org.qinan.safetyeval.adapter.web;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.qinan.safetyeval.client.api.FileStorageApi;
import org.qinan.safetyeval.client.co.FileInfoCO;
import org.qinan.safetyeval.client.dto.SingleResponse;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URL;
import java.util.List;

/**
 * 文件存储管理适配层（Controller）
 * <p>
 * 提供 filestorage 表的下载、删除、获取地址等 REST 接口。
 * 文件新增由 {@link FileUploadController} 在上传时同步完成。
 * </p>
 *
 * @author safety-eval
 */
@Api(tags = "文件存储管理")
@RestController
@RequestMapping("/safetyEval/file-storage")
public class FileStorageController {

    @Resource
    private FileStorageApi fileStorageApi;

    // ==================== 下载 ====================

    @ApiOperation("下载文件")
    @GetMapping("/download/{fileId}")
    public void download(
            @ApiParam("文件ID") @PathVariable Integer fileId,
            HttpServletResponse response) {
        try {
            SingleResponse<FileInfoCO> result = fileStorageApi.getPresignedUrl(fileId);
            if (!result.isSuccess() || result.getData() == null) {
                response.setStatus(HttpServletResponse.SC_NOT_FOUND);
                return;
            }
            FileInfoCO fileInfo = result.getData();

            response.setContentType(fileInfo.getContentType() != null ? fileInfo.getContentType() : "application/octet-stream");
            response.setHeader("Content-Disposition",
                    "attachment; filename=\"" + java.net.URLEncoder.encode(fileInfo.getOriginalFilename(), "UTF-8") + "\"");
            if (fileInfo.getSize() != null) {
                response.setContentLengthLong(fileInfo.getSize());
            }

            URL url = new URL(fileInfo.getPresignedUrl());
            try (java.io.InputStream in = url.openStream();
                 OutputStream out = response.getOutputStream()) {
                byte[] buffer = new byte[8192];
                int bytesRead;
                while ((bytesRead = in.read(buffer)) != -1) {
                    out.write(buffer, 0, bytesRead);
                }
                out.flush();
            }
        } catch (IOException e) {
            response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        }
    }

    // ==================== 获取地址/信息 ====================

    @ApiOperation("获取文件签名URL（临时访问链接）")
    @GetMapping("/presigned-url/{fileId}")
    public SingleResponse<FileInfoCO> getPresignedUrl(
            @ApiParam("文件ID") @PathVariable Integer fileId) {
        return fileStorageApi.getPresignedUrl(fileId);
    }

    @ApiOperation("获取文件信息")
    @GetMapping("/info/{fileId}")
    public SingleResponse<FileInfoCO> getInfo(
            @ApiParam("文件ID") @PathVariable Integer fileId) {
        return fileStorageApi.getInfo(fileId);
    }

    // ==================== 删除 ====================

    @ApiOperation("删除文件")
    @DeleteMapping("/delete/{fileId}")
    public SingleResponse<Void> delete(
            @ApiParam("文件ID") @PathVariable Integer fileId) {
        return fileStorageApi.delete(fileId);
    }

    @ApiOperation("批量删除文件")
    @DeleteMapping("/delete-batch")
    public SingleResponse<Void> deleteBatch(
            @ApiParam("文件ID列表") @RequestBody List<Integer> fileIds) {
        return fileStorageApi.deleteBatch(fileIds);
    }

    // ==================== 列表查询 ====================

    @ApiOperation("获取所有文件列表")
    @GetMapping("/list-all")
    public SingleResponse<List<FileInfoCO>> listAll() {
        return fileStorageApi.listAll();
    }

    @ApiOperation("根据上传者获取文件列表")
    @GetMapping("/list-by-creator")
    public SingleResponse<List<FileInfoCO>> listByCreator(
            @ApiParam("上传者UID") @RequestParam("creatorUid") String creatorUid) {
        return fileStorageApi.listByCreator(creatorUid);
    }
}
