package com.gcsc.connection.apikey.controller;

import com.gcsc.connection.apikey.dto.ApiKeyCreateResponse;
import com.gcsc.connection.apikey.dto.ApiKeyDetailResponse;
import com.gcsc.connection.apikey.dto.ApiKeyResponse;
import com.gcsc.connection.apikey.dto.CreateApiKeyRequest;
import com.gcsc.connection.apikey.dto.PermissionResponse;
import com.gcsc.connection.apikey.dto.UpdatePermissionsRequest;
import com.gcsc.connection.apikey.service.ApiKeyPermissionService;
import com.gcsc.connection.apikey.service.ApiKeyService;
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.RestController;

import java.util.List;

/**
 * API Key 관리 API
 */
@RestController
@RequestMapping("/api/keys")
@RequiredArgsConstructor
public class ApiKeyController {

    private final ApiKeyService apiKeyService;
    private final ApiKeyPermissionService apiKeyPermissionService;
    private final HttpServletRequest request;

    /**
     * 내 API Key 목록 조회
     */
    @GetMapping
    public ResponseEntity<ApiResponse<List<ApiKeyResponse>>> getMyKeys() {
        Long userId = getCurrentUserId();
        List<ApiKeyResponse> keys = apiKeyService.getMyKeys(userId);
        return ResponseEntity.ok(ApiResponse.ok(keys));
    }

    /**
     * 전체 API Key 목록 조회 (관리자용)
     */
    @GetMapping("/all")
    public ResponseEntity<ApiResponse<List<ApiKeyResponse>>> getAllKeys() {
        List<ApiKeyResponse> keys = apiKeyService.getAllKeys();
        return ResponseEntity.ok(ApiResponse.ok(keys));
    }

    /**
     * API Key 상세 조회 (복호화된 키 포함, 관리자 전용)
     */
    @GetMapping("/{id}")
    public ResponseEntity<ApiResponse<ApiKeyDetailResponse>> getKeyDetail(@PathVariable Long id) {
        ApiKeyDetailResponse detail = apiKeyService.getKeyDetail(id);
        return ResponseEntity.ok(ApiResponse.ok(detail));
    }

    /**
     * API Key 생성 (관리자 전용)
     */
    @PostMapping
    public ResponseEntity<ApiResponse<ApiKeyCreateResponse>> createKey(
            @RequestBody @Valid CreateApiKeyRequest request) {
        Long userId = getCurrentUserId();
        ApiKeyCreateResponse response = apiKeyService.createKey(userId, request);
        return ResponseEntity.ok(ApiResponse.ok(response));
    }

    /**
     * API Key 폐기
     */
    @PutMapping("/{id}/revoke")
    public ResponseEntity<ApiResponse<Void>> revokeKey(@PathVariable Long id) {
        apiKeyService.revokeKey(id);
        return ResponseEntity.ok(ApiResponse.ok(null, "API Key가 폐기되었습니다"));
    }

    /**
     * API Key 권한 목록 조회
     */
    @GetMapping("/{id}/permissions")
    public ResponseEntity<ApiResponse<List<PermissionResponse>>> getPermissions(@PathVariable Long id) {
        List<PermissionResponse> permissions = apiKeyPermissionService.getPermissions(id);
        return ResponseEntity.ok(ApiResponse.ok(permissions));
    }

    /**
     * API Key 권한 수정 (관리자/매니저 전용)
     */
    @PutMapping("/{id}/permissions")
    public ResponseEntity<ApiResponse<List<PermissionResponse>>> updatePermissions(
            @PathVariable Long id,
            @RequestBody @Valid UpdatePermissionsRequest request) {
        Long userId = getCurrentUserId();
        List<PermissionResponse> permissions = apiKeyPermissionService.updatePermissions(id, userId, request);
        return ResponseEntity.ok(ApiResponse.ok(permissions));
    }

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