package com.gcsc.connection.monitoring.controller;

import com.gcsc.connection.common.dto.ApiResponse;
import com.gcsc.connection.common.dto.PageResponse;
import com.gcsc.connection.monitoring.dto.RequestLogResponse;
import com.gcsc.connection.monitoring.dto.RequestLogSearchDto;
import com.gcsc.connection.monitoring.service.RequestLogService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Page;
import org.springframework.format.annotation.DateTimeFormat;
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.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.time.LocalDate;
import java.time.LocalDateTime;

/**
 * 요청 로그 조회 API
 */
@RestController
@RequestMapping("/api/monitoring")
@RequiredArgsConstructor
public class RequestLogController {

    private final RequestLogService requestLogService;

    /**
     * 요청 로그 검색
     */
    @GetMapping("/logs")
    public ResponseEntity<ApiResponse<PageResponse<RequestLogResponse>>> searchLogs(
        @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
        LocalDate startDate,
        @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE)
        LocalDate endDate,
        @RequestParam(required = false) Long serviceId,
        @RequestParam(required = false) String requestStatus,
        @RequestParam(required = false) String requestMethod,
        @RequestParam(required = false) String requestIp,
        @RequestParam(defaultValue = "0") int page,
        @RequestParam(defaultValue = "20") int size
    ) {
        LocalDateTime startDateTime = startDate != null ? startDate.atStartOfDay() : null;
        LocalDateTime endDateTime = endDate != null ? endDate.plusDays(1).atStartOfDay() : null;
        RequestLogSearchDto searchDto = new RequestLogSearchDto(
            startDateTime, endDateTime, serviceId, requestStatus, requestMethod, requestIp, page, size);
        Page<RequestLogResponse> result = requestLogService.searchLogs(searchDto);
        return ResponseEntity.ok(ApiResponse.ok(PageResponse.from(result)));
    }

    /**
     * 요청 로그 상세 조회
     */
    @GetMapping("/logs/{id}")
    public ResponseEntity<ApiResponse<RequestLogResponse>> getLogDetail(@PathVariable Long id) {
        return ResponseEntity.ok(ApiResponse.ok(requestLogService.getLogDetail(id)));
    }
}
