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.service.ActivityService;
import jakarta.validation.Valid;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

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

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

    private final ActivityService activityService;

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

    @PostMapping
    public ResponseEntity<ApiResponse<CreateApiKeyResponse>> createApiKey(@Valid @RequestBody CreateApiKeyRequest request) {
        String rawApiKey = activityService.generateApiKey(request);
        log.info("Created new API key for activity: {}", request.getActivityId());
        ApiResponse<CreateApiKeyResponse> response = ApiResponse.success(new CreateApiKeyResponse(rawApiKey));
        response.setCode(HttpStatus.CREATED.value());
        return new ResponseEntity<>(response, HttpStatus.CREATED);
    }

    @GetMapping("/{id}/reveal")
    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}")
    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));
    }

    @PostMapping("/{id}/use")
    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")
    public ResponseEntity<ApiResponse<Void>> validateApiKey(@Valid @RequestBody UseApiKeyRequest request) {
        activityService.validateApiKeyByPrefixAndMarkUsed(request.getApiKey());
        return ResponseEntity.ok(ApiResponse.success(null));
    }
}
