package com.mosquito.project.controller;

import com.mosquito.project.dto.CreateApiKeyRequest;
import com.mosquito.project.dto.CreateApiKeyResponse;
import com.mosquito.project.dto.ApiResponse;
import com.mosquito.project.dto.RevealApiKeyResponse;
import com.mosquito.project.dto.UseApiKeyRequest;
import com.mosquito.project.dto.ApiKeyListItemResponse;
import com.mosquito.project.permission.ApprovalFlowService;
import com.mosquito.project.permission.RequirePermission;
import com.mosquito.project.service.ActivityService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/v1/keys")
public class ApiKeyController {

    private static final Logger log = LoggerFactory.getLogger(ApiKeyController.class);

    // 业务类型常量
    private static final String BIZ_TYPE_API_KEY = "API_KEY_APPLY";

    private final ActivityService activityService;
    private final ApprovalFlowService approvalFlowService;

    public ApiKeyController(ActivityService activityService, ApprovalFlowService approvalFlowService) {
        this.activityService = activityService;
        this.approvalFlowService = approvalFlowService;
    }

    /**
     * 获取当前用户ID
     */
    private Long getCurrentUserId(HttpServletRequest request) {
        Object userIdObj = request.getAttribute("userId");
        if (userIdObj instanceof Long) {
            return (Long) userIdObj;
        } else if (userIdObj instanceof Integer) {
            return ((Integer) userIdObj).longValue();
        } else if (userIdObj instanceof String) {
            try {
                return Long.parseLong((String) userIdObj);
            } catch (NumberFormatException e) {
                return null;
            }
        }
        return null;
    }

    /**
     * 获取API Key列表
     */
    @GetMapping
    @RequirePermission("system.api-key.view.ALL")
    public ResponseEntity<ApiResponse<List<ApiKeyListItemResponse>>> listApiKeys() {
        List<ApiKeyListItemResponse> list = activityService.listApiKeys();
        log.info("Listed API keys, count: {}", list.size());
        return ResponseEntity.ok(ApiResponse.success(list));
    }

    @PostMapping
    @RequirePermission("system.api-key.create.ALL")
    public ResponseEntity<ApiResponse<Map<String, Object>>> createApiKey(
            @Valid @RequestBody CreateApiKeyRequest request,
            HttpServletRequest httpRequest) {

        Long currentUserId = getCurrentUserId(httpRequest);

        if (currentUserId == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED)
                .body(ApiResponse.error(401, "无法获取当前用户信息"));
        }

        // 先保存待审批的API Key（创建禁用状态）
        Long pendingId = activityService.savePendingApiKey(request);

        // 尝试提交审批
        try {
            String bizData = String.format("{\"activityId\":%d,\"name\":\"%s\"}",
                request.getActivityId(), request.getName() != null ? request.getName() : "");

            Map<String, Object> approvalResult = approvalFlowService.submitApprovalByEvent(
                "API_KEY_APPLY",
                BIZ_TYPE_API_KEY,
                pendingId,
                "API Key申请审批",
                currentUserId,
                "申请创建API Key",
                bizData
            );

            Map<String, Object> result = new HashMap<>();
            result.put("apiKeyId", pendingId);
            result.put("recordId", approvalResult.get("recordId"));
            result.put("status", "PENDING_APPROVAL");
            result.put("message", "API Key已提交审批，审批通过后生效");

            return ResponseEntity.ok(ApiResponse.success(result, "API Key已提交审批"));
        } catch (Exception e) {
            // 审批失败，尝试回滚待审批的 API Key 记录
            log.error("提交审批失败，拒绝创建API Key: error={}", e.getMessage());
            if (pendingId != null) {
                try {
                    activityService.revokeApiKey(pendingId);
                } catch (Exception rollbackError) {
                    log.warn("审批失败后回滚API Key记录失败: apiKeyId={}, error={}", pendingId, rollbackError.getMessage());
                }
            }
            return ResponseEntity.status(HttpStatus.CONFLICT)
                .body(ApiResponse.error(409, "审批服务异常，无法执行敏感操作"));
        }
    }

    @GetMapping("/{id}/reveal")
    @RequirePermission("system.api-key.view.ALL")
    public ResponseEntity<ApiResponse<RevealApiKeyResponse>> revealApiKey(@PathVariable Long id) {
        log.warn("API key revealed for id: {} - ensure this is logged and monitored", id);
        String rawApiKey = activityService.revealApiKey(id);
        RevealApiKeyResponse payload = new RevealApiKeyResponse(
            rawApiKey,
            "警告: API密钥只显示一次，请立即保存！此操作会被记录。"
        );
        return ResponseEntity.ok(ApiResponse.success(payload));
    }

    @DeleteMapping("/{id}")
    @RequirePermission("system.api-key.delete.ALL")
    public ResponseEntity<ApiResponse<Void>> revokeApiKey(@PathVariable Long id) {
        activityService.revokeApiKey(id);
        log.info("API key revoked for id: {}", id);
        return ResponseEntity.ok(ApiResponse.success(null));
    }

    /**
     * 启用API Key
     */
    @PostMapping("/{id}/enable")
    @RequirePermission("system.api-key.enable.ALL")
    public ResponseEntity<ApiResponse<Void>> enableApiKey(@PathVariable Long id) {
        activityService.enableApiKey(id);
        log.info("API key enabled for id: {}", id);
        return ResponseEntity.ok(ApiResponse.success(null));
    }

    /**
     * 禁用API Key
     */
    @PostMapping("/{id}/disable")
    @RequirePermission("system.api-key.disable.ALL")
    public ResponseEntity<ApiResponse<Void>> disableApiKey(@PathVariable Long id) {
        activityService.disableApiKey(id);
        log.info("API key disabled for id: {}", id);
        return ResponseEntity.ok(ApiResponse.success(null));
    }

    /**
     * 重置API Key
     */
    @PostMapping("/{id}/reset")
    @RequirePermission("system.api-key.reset.ALL")
    public ResponseEntity<ApiResponse<CreateApiKeyResponse>> resetApiKey(@PathVariable Long id) {
        String newRawApiKey = activityService.resetApiKey(id);
        log.info("API key reset for id: {}", id);
        return ResponseEntity.ok(ApiResponse.success(new CreateApiKeyResponse(newRawApiKey)));
    }

    @PostMapping("/{id}/use")
    @RequirePermission("system.api-key.manage.ALL")
    public ResponseEntity<ApiResponse<Void>> useApiKey(@PathVariable Long id, @Valid @RequestBody UseApiKeyRequest request) {
        activityService.validateAndMarkApiKeyUsed(id, request.getApiKey());
        return ResponseEntity.ok(ApiResponse.success(null));
    }

    @PostMapping("/validate")
    @RequirePermission("system.api-key.manage.ALL")
    public ResponseEntity<ApiResponse<Void>> validateApiKey(@Valid @RequestBody UseApiKeyRequest request) {
        activityService.validateApiKeyByPrefixAndMarkUsed(request.getApiKey());
        return ResponseEntity.ok(ApiResponse.success(null));
    }
}
