package top.tqx.demo_1.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.tqx.demo_1.common.Result;
import top.tqx.demo_1.dto.ExpireTimeRequest;
import top.tqx.demo_1.dto.FilePermissionRequest;
import top.tqx.demo_1.entity.FilePermission;
import top.tqx.demo_1.service.FilePermissionService;

import java.util.List;

@Tag(name = "文件权限管理", description = "文件权限的授权和撤销")
@RestController
@RequestMapping("/file/permission")
public class FilePermissionController extends BaseController {

    private final FilePermissionService filePermissionService;

    public FilePermissionController(FilePermissionService filePermissionService) {
        this.filePermissionService = filePermissionService;
    }

    @Operation(summary = "授权文件权限", description = "为用户或部门授予文件访问权限")
    @PostMapping
    public Result<Void> grantPermission(
            @RequestBody FilePermissionRequest request,
            HttpServletRequest httpRequest) {
        Long userId = getCurrentUserId(httpRequest);
        if (userId == null) {
            return error("用户未登录");
        }
        request.setGrantUserId(userId);
        filePermissionService.grantFilePermission(request);
        return success();
    }

    @Operation(summary = "撤销文件权限", description = "撤销用户或部门的文件访问权限")
    @DeleteMapping("/{id}")
    public Result<Void> revokePermission(
            @Parameter(description = "权限ID") @PathVariable Long id) {
        filePermissionService.revokeFilePermission(id);
        return success();
    }

    @Operation(summary = "查询文件权限列表", description = "获取文件的所有权限信息")
    @GetMapping("/file/{fileId}")
    public Result<List<FilePermission>> getFilePermissions(
            @Parameter(description = "文件ID") @PathVariable Long fileId,
            HttpServletRequest httpRequest) {
        Long userId = getCurrentUserId(httpRequest);
        List<FilePermission> permissions = filePermissionService.getUserFilePermissions(userId, fileId);
        return success(permissions);
    }

    @Operation(summary = "更新权限过期时间", description = "修改权限的过期时间")
    @PutMapping("/{id}/expire")
    public Result<Void> updateExpireTime(
            @Parameter(description = "权限ID") @PathVariable Long id,
            @RequestBody ExpireTimeRequest request) {
        filePermissionService.updatePermissionExpire(id, request.getExpireTime());
        return success();
    }
}