package com.gcsc.connection.apihub.controller;

import com.gcsc.connection.apihub.dto.PopularApiResponse;
import com.gcsc.connection.apihub.dto.RecentApiResponse;
import com.gcsc.connection.apihub.dto.ServiceCatalogResponse;
import com.gcsc.connection.apihub.service.ApiHubService;
import com.gcsc.connection.common.dto.ApiResponse;
import com.gcsc.connection.service.dto.ApiDetailResponse;
import com.gcsc.connection.service.service.ServiceManagementService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * API Hub 카탈로그 및 API 상세 조회 컨트롤러
 */
@RestController
@RequestMapping("/api/api-hub")
@RequiredArgsConstructor
public class ApiHubController {

    private final ApiHubService apiHubService;
    private final ServiceManagementService serviceManagementService;

    /**
     * 활성 서비스와 해당 서비스의 활성 API를 도메인별로 그룹화하여 카탈로그 형태로 반환
     */
    @GetMapping("/catalog")
    public ResponseEntity<ApiResponse<List<ServiceCatalogResponse>>> getCatalog() {
        List<ServiceCatalogResponse> catalog = apiHubService.getCatalog();
        return ResponseEntity.ok(ApiResponse.ok(catalog));
    }

    /**
     * 최근 등록된 활성 API 상위 10건 반환
     */
    @GetMapping("/recent-apis")
    public ResponseEntity<ApiResponse<List<RecentApiResponse>>> getRecentApis() {
        List<RecentApiResponse> recentApis = apiHubService.getRecentApis();
        return ResponseEntity.ok(ApiResponse.ok(recentApis));
    }

    /**
     * 인기 API (최근 1주일 기준 호출 수 Top N)
     */
    @GetMapping("/popular-apis")
    public ResponseEntity<ApiResponse<List<PopularApiResponse>>> getPopularApis() {
        List<PopularApiResponse> popularApis = apiHubService.getPopularApis(3);
        return ResponseEntity.ok(ApiResponse.ok(popularApis));
    }

    /**
     * 서비스 단건 카탈로그 조회
     */
    @GetMapping("/services/{serviceId}")
    public ResponseEntity<ApiResponse<ServiceCatalogResponse>> getServiceCatalog(
            @PathVariable Long serviceId) {
        ServiceCatalogResponse catalog = apiHubService.getServiceCatalog(serviceId);
        return ResponseEntity.ok(ApiResponse.ok(catalog));
    }

    /**
     * API 상세 명세 조회
     */
    @GetMapping("/services/{serviceId}/apis/{apiId}")
    public ResponseEntity<ApiResponse<ApiDetailResponse>> getApiDetail(
            @PathVariable Long serviceId, @PathVariable Long apiId) {
        ApiDetailResponse detail = serviceManagementService.getApiDetail(serviceId, apiId);
        return ResponseEntity.ok(ApiResponse.ok(detail));
    }
}
