package com.writeoff.module.file.controller;

import com.writeoff.common.api.ApiResponse;
import com.writeoff.common.exception.BusinessException;
import com.writeoff.module.file.service.OssService;
import com.writeoff.module.system.service.DataPermissionService;
import com.writeoff.security.AuthContext;
import com.writeoff.security.AuthScope;
import com.writeoff.security.PermissionService;
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.LinkedHashMap;
import java.util.Map;

@RestController
@RequestMapping("/api/files")
public class FileController {
    private final OssService ossService;
    private final DataPermissionService dataPermissionService;
    private final PermissionService permissionService;

    public FileController(OssService ossService, DataPermissionService dataPermissionService, PermissionService permissionService) {
        this.ossService = ossService;
        this.dataPermissionService = dataPermissionService;
        this.permissionService = permissionService;
    }

    @GetMapping("/presign-download")
    public ApiResponse<Map<String, Object>> presignDownload(@RequestParam String objectKey) {
        Long userId = AuthContext.userId();
        if (userId == null) {
            throw new BusinessException(10002, "未登录");
        }
        AuthScope scope = AuthContext.scope();
        if (scope == AuthScope.PLATFORM) {
            if (!permissionService.hasPlatformPermission(userId, "file.download")) {
                throw new BusinessException(10004, "无操作权限");
            }
        } else {
            if (!permissionService.hasPermission(userId, "file.download")) {
                throw new BusinessException(10004, "无操作权限");
            }
        }
        String signedUrl = ossService.generateDownloadUrl(objectKey);
        Map<String, Object> result = new LinkedHashMap<>();
        result.put("objectKey", objectKey);
        result.put("signedUrl", signedUrl);
        return ApiResponse.success(result);
    }
}
