package com.mosquito.project.controller;

import com.mosquito.project.dto.ApiKeyCreateRequest;
import com.mosquito.project.dto.ApiKeyResponse;
import com.mosquito.project.service.ApiKeySecurityService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.Map;
import java.util.Optional;

/**
 * API密钥安全控制器
 * 提供密钥的恢复、轮换等安全功能
 */
@Slf4j
@RestController
@RequestMapping("/api/v1/api-keys")
@Tag(name = "API Key Security", description = "API密钥安全管理")
@RequiredArgsConstructor
public class ApiKeySecurityController {

    private final ApiKeySecurityService apiKeySecurityService;

    /**
     * 重新显示API密钥
     */
    @PostMapping("/{id}/reveal")
    @Operation(summary = "重新显示API密钥", description = "在验证权限后重新显示API密钥")
    public ResponseEntity<ApiKeyResponse> revealApiKey(
            @PathVariable Long id,
            @RequestBody Map<String, String> request) {
        
        String verificationCode = request.get("verificationCode");
        Optional<String> rawKey = apiKeySecurityService.revealApiKey(id, verificationCode);
        
        if (rawKey.isPresent()) {
            log.info("API key revealed successfully for id: {}", id);
            return ResponseEntity.ok(
                new ApiKeyResponse("API密钥重新显示成功", rawKey.get())
            );
        } else {
            return ResponseEntity.notFound().build();
        }
    }

    /**
     * 轮换API密钥
     */
    @PostMapping("/{id}/rotate")
    @Operation(summary = "轮换API密钥", description = "撤销旧密钥并生成新密钥")
    public ResponseEntity<ApiKeyResponse> rotateApiKey(
            @PathVariable Long id) {
        
        try {
            var newApiKey = apiKeySecurityService.rotateApiKey(id);
            log.info("API key rotated successfully for id: {}", id);
            
            return ResponseEntity.ok(
                new ApiKeyResponse("API密钥轮换成功", 
                    "新密钥已生成，请妥善保存。旧密钥已撤销。")
            );
        } catch (Exception e) {
            log.error("Failed to rotate API key: {}", id, e);
            return ResponseEntity.badRequest()
                .body(new ApiKeyResponse("轮换失败", e.getMessage()));
        }
    }

    /**
     * 获取API密钥使用信息
     */
    @GetMapping("/{id}/info")
    @Operation(summary = "获取API密钥信息", description = "获取API密钥的使用统计和安全状态")
    public ResponseEntity<Map<String, Object>> getApiKeyInfo(@PathVariable Long id) {
        // 这里可以添加密钥使用统计、最后访问时间等信息
        Map<String, Object> info = Map.of(
            "apiKeyId", id,
            "status", "active",
            "lastAccess", System.currentTimeMillis(),
            "rotationAvailable", true
        );
        
        return ResponseEntity.ok(info);
    }
}