package com.gcsc.connection.apikey.controller;

import com.gcsc.connection.apikey.dto.ApiKeyCreateResponse;
import com.gcsc.connection.apikey.dto.ApiKeyRequestCreateDto;
import com.gcsc.connection.apikey.dto.ApiKeyRequestResponse;
import com.gcsc.connection.apikey.dto.ApiKeyRequestReviewDto;
import com.gcsc.connection.apikey.service.ApiKeyRequestService;
import com.gcsc.connection.common.dto.ApiResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * API Key 신청/심사 API
 */
@RestController
@RequestMapping("/api/keys/requests")
@RequiredArgsConstructor
public class ApiKeyRequestController {

    private final ApiKeyRequestService apiKeyRequestService;
    private final HttpServletRequest request;

    /**
     * API Key 신청 생성
     */
    @PostMapping
    public ResponseEntity<ApiResponse<ApiKeyRequestResponse>> createRequest(
            @RequestBody @Valid ApiKeyRequestCreateDto request) {
        Long userId = getCurrentUserId();
        ApiKeyRequestResponse response = apiKeyRequestService.createRequest(userId, request);
        return ResponseEntity.ok(ApiResponse.ok(response));
    }

    /**
     * 내 신청 목록 조회
     */
    @GetMapping("/my")
    public ResponseEntity<ApiResponse<List<ApiKeyRequestResponse>>> getMyRequests() {
        Long userId = getCurrentUserId();
        List<ApiKeyRequestResponse> responses = apiKeyRequestService.getMyRequests(userId);
        return ResponseEntity.ok(ApiResponse.ok(responses));
    }

    /**
     * 신청 목록 조회 (관리자/매니저용)
     */
    @GetMapping
    public ResponseEntity<ApiResponse<List<ApiKeyRequestResponse>>> getRequests(
            @RequestParam(required = false) String status) {
        List<ApiKeyRequestResponse> responses;
        if ("PENDING".equalsIgnoreCase(status)) {
            responses = apiKeyRequestService.getPendingRequests();
        } else {
            responses = apiKeyRequestService.getAllRequests();
        }
        return ResponseEntity.ok(ApiResponse.ok(responses));
    }

    /**
     * 신청 심사 (승인/거절)
     */
    @PutMapping("/{id}/review")
    public ResponseEntity<ApiResponse<ApiKeyCreateResponse>> reviewRequest(
            @PathVariable Long id,
            @RequestBody @Valid ApiKeyRequestReviewDto request) {
        Long reviewerId = getCurrentUserId();
        ApiKeyCreateResponse response = apiKeyRequestService.reviewRequest(id, reviewerId, request);
        if (response != null) {
            return ResponseEntity.ok(ApiResponse.ok(response, "신청이 승인되었습니다"));
        }
        return ResponseEntity.ok(ApiResponse.ok(null, "신청이 거절되었습니다"));
    }

    private Long getCurrentUserId() {
        String userIdHeader = request.getHeader("X-User-Id");
        if (userIdHeader != null && !userIdHeader.isBlank()) {
            return Long.parseLong(userIdHeader);
        }
        try {
            return Long.parseLong(SecurityContextHolder.getContext().getAuthentication().getName());
        } catch (Exception e) {
            return 1L;
        }
    }
}
