package com.dora.controller;

import com.dora.common.Result;
import com.dora.dto.ApiKeyDTO;
import com.dora.service.ApiKeyService;
import com.dora.util.SecurityUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.ExampleObject;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.responses.ApiResponses;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

/**
 * API密钥控制器
 */
@Tag(name = "API密钥管理", description = "API密钥相关接口，只有会员用户才能使用")
@RestController
@RequestMapping("/user/v1/api-key")
public class ApiKeyController {

    @Autowired
    private ApiKeyService apiKeyService;

    /**
     * 生成API密钥
     */
    @Operation(
        summary = "生成API密钥", 
        description = "只有VIP(角色2)和SVIP(角色3)用户才能生成API密钥。每个用户只能有一个API密钥。"
    )
    @ApiResponses(value = {
        @ApiResponse(
            responseCode = "200", 
            description = "生成成功",
            content = @Content(
                mediaType = "application/json",
                schema = @Schema(implementation = ApiKeyDTO.class),
                examples = @ExampleObject(
                    value = """
                    {
                      "code": 200,
                      "message": "success",
                      "data": {
                        "keyValue": "ak_1234567890abcdef1234567890abcdef",
                        "isActive": true,
                        "lastUsedAt": null,
                        "createTime": "2024-12-01T10:00:00",
                        "membershipExpiresAt": "2025-01-01T10:00:00",
                        "userRole": 2
                      }
                    }
                    """
                )
            )
        ),
        @ApiResponse(
            responseCode = "403", 
            description = "权限不足，只有会员用户才能生成API密钥",
            content = @Content(
                mediaType = "application/json",
                examples = @ExampleObject(
                    value = """
                    {
                      "code": 403,
                      "message": "只有会员用户才能生成API密钥",
                      "data": null
                    }
                    """
                )
            )
        ),
        @ApiResponse(
            responseCode = "409", 
            description = "用户已有API密钥",
            content = @Content(
                mediaType = "application/json",
                examples = @ExampleObject(
                    value = """
                    {
                      "code": 409,
                      "message": "用户已有API密钥，请先删除现有密钥",
                      "data": null
                    }
                    """
                )
            )
        )
    })
    @PostMapping("/generate")
    public Result<ApiKeyDTO> generateApiKey() {
        try {
            Long userId = SecurityUtil.getCurrentUserId();
            ApiKeyDTO apiKeyDTO = apiKeyService.generateApiKey(userId);
            return Result.success(apiKeyDTO);
        } catch (RuntimeException e) {
            return Result.error(401, e.getMessage());
        } catch (Exception e) {
            return Result.error(500, e.getMessage());
        }
    }

    /**
     * 刷新API密钥
     */
    @Operation(
        summary = "刷新API密钥", 
        description = "生成新的API密钥值，替换原有的密钥。旧密钥立即失效。"
    )
    @ApiResponses(value = {
        @ApiResponse(
            responseCode = "200", 
            description = "刷新成功",
            content = @Content(
                mediaType = "application/json",
                schema = @Schema(implementation = ApiKeyDTO.class),
                examples = @ExampleObject(
                    value = """
                    {
                      "code": 200,
                      "message": "success",
                      "data": {
                        "keyValue": "ak_new1234567890abcdef1234567890abcdef",
                        "isActive": true,
                        "lastUsedAt": null,
                        "createTime": "2024-12-01T10:00:00",
                        "membershipExpiresAt": "2025-01-01T10:00:00",
                        "userRole": 2
                      }
                    }
                    """
                )
            )
        ),
        @ApiResponse(
            responseCode = "404", 
            description = "用户没有API密钥",
            content = @Content(
                mediaType = "application/json",
                examples = @ExampleObject(
                    value = """
                    {
                      "code": 404,
                      "message": "用户没有API密钥，请先生成",
                      "data": null
                    }
                    """
                )
            )
        )
    })
    @PostMapping("/refresh")
    public Result<ApiKeyDTO> refreshApiKey() {
        try {
            Long userId = SecurityUtil.getCurrentUserId();
            ApiKeyDTO apiKeyDTO = apiKeyService.refreshApiKey(userId);
            return Result.success(apiKeyDTO);
        } catch (RuntimeException e) {
            return Result.error(401, e.getMessage());
        } catch (Exception e) {
            return Result.error(500, e.getMessage());
        }
    }

    /**
     * 删除API密钥
     */
    @Operation(
        summary = "删除API密钥", 
        description = "删除用户的API密钥。删除后需要重新生成才能使用API接口。"
    )
    @ApiResponses(value = {
        @ApiResponse(
            responseCode = "200", 
            description = "删除成功",
            content = @Content(
                mediaType = "application/json",
                examples = @ExampleObject(
                    value = """
                    {
                      "code": 200,
                      "message": "success",
                      "data": "API密钥删除成功"
                    }
                    """
                )
            )
        ),
        @ApiResponse(
            responseCode = "404", 
            description = "用户没有API密钥",
            content = @Content(
                mediaType = "application/json",
                examples = @ExampleObject(
                    value = """
                    {
                      "code": 404,
                      "message": "用户没有API密钥",
                      "data": null
                    }
                    """
                )
            )
        )
    })
    @DeleteMapping("/delete")
    public Result<String> deleteApiKey() {
        try {
            Long userId = SecurityUtil.getCurrentUserId();
            apiKeyService.deleteApiKey(userId);
            return Result.success("API密钥删除成功");
        } catch (RuntimeException e) {
            return Result.error(401, e.getMessage());
        } catch (Exception e) {
            return Result.error(500, e.getMessage());
        }
    }

    /**
     * 获取API密钥信息
     */
    @Operation(
        summary = "获取API密钥信息", 
        description = "获取当前用户的API密钥信息，包括密钥值、状态、过期时间等"
    )
    @ApiResponses(value = {
        @ApiResponse(
            responseCode = "200", 
            description = "获取成功",
            content = @Content(
                mediaType = "application/json",
                schema = @Schema(implementation = ApiKeyDTO.class),
                examples = @ExampleObject(
                    value = """
                    {
                      "code": 200,
                      "message": "success",
                      "data": {
                        "keyValue": "ak_1234567890abcdef1234567890abcdef",
                        "isActive": true,
                        "lastUsedAt": "2024-12-01T15:30:00",
                        "createTime": "2024-12-01T10:00:00",
                        "membershipExpiresAt": "2025-01-01T10:00:00",
                        "userRole": 2
                      }
                    }
                    """
                )
            )
        ),
        @ApiResponse(
            responseCode = "404", 
            description = "用户没有API密钥",
            content = @Content(
                mediaType = "application/json",
                examples = @ExampleObject(
                    value = """
                    {
                      "code": 404,
                      "message": "用户没有API密钥",
                      "data": null
                    }
                    """
                )
            )
        )
    })
    @GetMapping("/info")
    public Result<ApiKeyDTO> getApiKeyInfo() {
        try {
            Long userId = SecurityUtil.getCurrentUserId();
            ApiKeyDTO apiKeyDTO = apiKeyService.getApiKey(userId);
            if (apiKeyDTO == null) {
                return Result.error(404, "用户没有API密钥");
            }
            return Result.success(apiKeyDTO);
        } catch (RuntimeException e) {
            return Result.error(401, e.getMessage());
        } catch (Exception e) {
            return Result.error(500, e.getMessage());
        }
    }

    /**
     * 验证API密钥（兼容接口）
     */
    @Operation(
        summary = "验证API密钥", 
        description = "验证当前用户的API密钥是否有效。返回true表示有效，false表示无效。只能验证当前登录用户自己的API密钥，确保安全性。支持两种传参方式：1) URL参数keyValue 2) POST请求体中的keyValue字段。建议使用请求体方式确保安全性。"
    )
    @ApiResponses(value = {
        @ApiResponse(
            responseCode = "200", 
            description = "验证成功",
            content = @Content(
                mediaType = "application/json",
                examples = @ExampleObject(
                    value = """
                    {
                      "code": 200,
                      "message": "success",
                      "data": true
                    }
                    """
                )
            )
        ),
        @ApiResponse(
            responseCode = "200", 
            description = "验证失败",
            content = @Content(
                mediaType = "application/json",
                examples = @ExampleObject(
                    value = """
                    {
                      "code": 200,
                      "message": "success",
                      "data": false
                    }
                    """
                )
            )
        ),
        @ApiResponse(
            responseCode = "401", 
            description = "用户未登录",
            content = @Content(
                mediaType = "application/json",
                examples = @ExampleObject(
                    value = """
                    {
                      "code": 401,
                      "message": "用户未登录",
                      "data": null
                    }
                    """
                )
            )
        )
    })
    @PostMapping("/validate")
    public Result<Object> validateApiKey(
        @Parameter(description = "API密钥值（URL参数方式）", example = "ak_1234567890abcdef1234567890abcdef")
        @RequestParam(required = false) String keyValue,
        @io.swagger.v3.oas.annotations.parameters.RequestBody(
            description = "API密钥验证请求（请求体方式）",
            required = false,
            content = @Content(
                mediaType = "application/json",
                schema = @Schema(implementation = ApiKeyDTO.ValidityCheckRequest.class),
                examples = @ExampleObject(
                    value = """
                    {
                      "keyValue": "ak_1234567890abcdef1234567890abcdef"
                    }
                    """
                )
            )
        )
        @RequestBody(required = false) ApiKeyDTO.ValidityCheckRequest request
    ) {
        try {
            // 获取当前用户ID
            Long currentUserId = SecurityUtil.getCurrentUserId();
            if (currentUserId == null) {
                return Result.error(401, "用户未登录");
            }
            
            // 兼容两种传参方式：URL参数 或 请求体
            String actualKeyValue = null;
            
            if (keyValue != null && !keyValue.trim().isEmpty()) {
                // 使用URL参数
                actualKeyValue = keyValue;
            } else if (request != null && request.getKeyValue() != null && !request.getKeyValue().trim().isEmpty()) {
                // 使用请求体参数
                actualKeyValue = request.getKeyValue();
            }
            
            if (actualKeyValue == null || actualKeyValue.trim().isEmpty()) {
                return Result.error(400, "API密钥不能为空，请通过URL参数keyValue或请求体中的keyValue字段传递");
            }
            
            // 验证API密钥是否属于当前用户并且有效（获取详细结果）
            ApiKeyService.ApiKeyValidationResult validationResult = apiKeyService.validateApiKeyForUserDetailed(actualKeyValue, currentUserId);
            return Result.success(validationResult.isValid(), validationResult.getMessage());
        } catch (Exception e) {
            return Result.error(500, e.getMessage());
        }
    }

    /**
     * 检查API密钥有效期状态
     */
    @Operation(
        summary = "检查API密钥有效期", 
        description = "检查当前用户的API密钥有效期状态，返回详细的验证信息包括用户信息、会员状态等。只能检查当前登录用户自己的API密钥，确保安全性。通过请求体传递API密钥，确保安全性。"
    )
    @ApiResponses(value = {
        @ApiResponse(
            responseCode = "200", 
            description = "检查成功",
            content = @Content(
                mediaType = "application/json",
                schema = @Schema(implementation = ApiKeyDTO.ValidityCheckResponse.class),
                examples = @ExampleObject(
                    value = """
                    {
                      "code": 200,
                      "message": "success",
                      "data": {
                        "isValid": true,
                        "failureReason": null,
                        "userInfo": {
                          "userId": 123456,
                          "username": "user123",
                          "role": 2,
                          "membershipExpiresAt": "2025-01-01T10:00:00",
                          "isMember": true,
                          "isExpired": false
                        },
                        "keyInfo": {
                          "keyValueMasked": "ak_1234****abcdef",
                          "isActive": true,
                          "createTime": "2024-12-01T10:00:00",
                          "lastUsedAt": "2024-12-01T15:30:00"
                        }
                      }
                    }
                    """
                )
            )
        ),
        @ApiResponse(
            responseCode = "200", 
            description = "API密钥无效或无权访问",
            content = @Content(
                mediaType = "application/json",
                examples = {
                    @ExampleObject(
                        name = "会员过期",
                        value = """
                        {
                          "code": 200,
                          "message": "success",
                          "data": {
                            "isValid": false,
                            "failureReason": "会员已过期",
                            "userInfo": null,
                            "keyInfo": null
                          }
                        }
                        """
                    ),
                    @ExampleObject(
                        name = "无权访问",
                        value = """
                        {
                          "code": 200,
                          "message": "success",
                          "data": {
                            "isValid": false,
                            "failureReason": "无权访问此API密钥",
                            "userInfo": null,
                            "keyInfo": null
                          }
                        }
                        """
                    )
                }
            )
        ),
        @ApiResponse(
            responseCode = "401", 
            description = "用户未登录",
            content = @Content(
                mediaType = "application/json",
                examples = @ExampleObject(
                    value = """
                    {
                      "code": 401,
                      "message": "用户未登录",
                      "data": null
                    }
                    """
                )
            )
        )
    })
    @PostMapping("/check-validity")
    public Result<ApiKeyDTO.ValidityCheckResponse> checkApiKeyValidity(
        @io.swagger.v3.oas.annotations.parameters.RequestBody(
            description = "API密钥验证请求",
            required = true,
            content = @Content(
                mediaType = "application/json",
                schema = @Schema(implementation = ApiKeyDTO.ValidityCheckRequest.class),
                examples = @ExampleObject(
                    value = """
                    {
                      "keyValue": "ak_1234567890abcdef1234567890abcdef"
                    }
                    """
                )
            )
        )
        @Valid @RequestBody ApiKeyDTO.ValidityCheckRequest request
    ) {
        try {
            // 获取当前用户ID
            Long currentUserId = SecurityUtil.getCurrentUserId();
            if (currentUserId == null) {
                return Result.error(401, "用户未登录");
            }
            
            ApiKeyDTO.ValidityCheckResponse response = apiKeyService.checkApiKeyValidityForUser(request.getKeyValue(), currentUserId);
            return Result.success(response);
        } catch (Exception e) {
            return Result.error(500, "检查API密钥有效期失败：" + e.getMessage());
        }
    }
} 