package com.dora.controller;

import com.dora.common.Result;
import com.dora.entity.User;
import io.swagger.v3.oas.annotations.Operation;
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 org.springframework.web.bind.annotation.*;

import jakarta.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * 外部API控制器
 * 需要API密钥验证的接口
 */
@Tag(name = "外部API", description = "需要API密钥验证的外部接口，请在请求头中添加 X-API-Key")
@RestController
@RequestMapping("/user/v1/external")
public class ExternalApiController {

    /**
     * 获取用户信息
     */
    @Operation(
        summary = "获取用户信息", 
        description = "通过API密钥获取当前用户信息。需要在请求头中添加 X-API-Key。"
    )
    @ApiResponses(value = {
        @ApiResponse(
            responseCode = "200", 
            description = "获取成功",
            content = @Content(
                mediaType = "application/json",
                examples = @ExampleObject(
                    value = """
                    {
                      "code": 200,
                      "message": "success",
                      "data": {
                        "userId": 1234567890,
                        "username": "用户123",
                        "role": 2,
                        "membershipExpiresAt": "2025-01-01T10:00:00"
                      }
                    }
                    """
                )
            )
        ),
        @ApiResponse(
            responseCode = "401", 
            description = "API密钥无效或已过期",
            content = @Content(
                mediaType = "application/json",
                examples = @ExampleObject(
                    value = """
                    {
                      "code": 401,
                      "message": "API密钥无效或已过期",
                      "data": null
                    }
                    """
                )
            )
        )
    })
    @GetMapping("/user/info")
    public Result<Map<String, Object>> getUserInfo(HttpServletRequest request) {
        User user = (User) request.getAttribute("currentUser");
        
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("userId", user.getId());
        userInfo.put("username", user.getUsername());
        userInfo.put("role", user.getRole());
        userInfo.put("membershipExpiresAt", user.getMembershipExpiresAt());
        
        return Result.success(userInfo);
    }

    /**
     * 测试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": {
                        "message": "API密钥验证成功",
                        "userId": 1234567890,
                        "timestamp": 1703123456789
                      }
                    }
                    """
                )
            )
        ),
        @ApiResponse(
            responseCode = "401", 
            description = "API密钥无效或已过期",
            content = @Content(
                mediaType = "application/json",
                examples = @ExampleObject(
                    value = """
                    {
                      "code": 401,
                      "message": "API密钥无效或已过期",
                      "data": null
                    }
                    """
                )
            )
        )
    })
    @PostMapping("/test")
    public Result<Map<String, Object>> testApi(HttpServletRequest request) {
        User user = (User) request.getAttribute("currentUser");
        
        Map<String, Object> result = new HashMap<>();
        result.put("message", "API密钥验证成功");
        result.put("userId", user.getId());
        result.put("timestamp", System.currentTimeMillis());
        
        return Result.success(result);
    }

    /**
     * 获取用户权限信息
     */
    @Operation(
        summary = "获取权限信息", 
        description = "获取当前用户的权限信息，包括是否可以访问API、用户角色、会员状态等"
    )
    @ApiResponses(value = {
        @ApiResponse(
            responseCode = "200", 
            description = "获取成功",
            content = @Content(
                mediaType = "application/json",
                examples = @ExampleObject(
                    value = """
                    {
                      "code": 200,
                      "message": "success",
                      "data": {
                        "canUseApi": true,
                        "userRole": 2,
                        "isMembershipValid": true
                      }
                    }
                    """
                )
            )
        ),
        @ApiResponse(
            responseCode = "401", 
            description = "API密钥无效或已过期",
            content = @Content(
                mediaType = "application/json",
                examples = @ExampleObject(
                    value = """
                    {
                      "code": 401,
                      "message": "API密钥无效或已过期",
                      "data": null
                    }
                    """
                )
            )
        )
    })
    @GetMapping("/user/permissions")
    public Result<Map<String, Object>> getUserPermissions(HttpServletRequest request) {
        User user = (User) request.getAttribute("currentUser");
        
        Map<String, Object> permissions = new HashMap<>();
        permissions.put("canUseApi", user.getRole() >= 2);
        permissions.put("userRole", user.getRole());
        permissions.put("isMembershipValid", user.getMembershipExpiresAt() == null || 
                      user.getMembershipExpiresAt().isAfter(java.time.LocalDateTime.now()));
        
        return Result.success(permissions);
    }
} 