package com.devjob.application.client;

import com.devjob.common.dto.ApiResponse;
import com.devjob.application.dto.JobInfo;
import com.devjob.common.exception.BusinessException;
import com.devjob.common.exception.ErrorCode;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestClientException;
import org.springframework.web.client.RestClient;

/**
 * EP08: devjob-job 서비스를 호출하는 임시 클라이언트.
 * - URL이 하드코딩되어 있고, 장애 시 별도 처리(Fallback)가 없다.
 * - EP15~17(Eureka)에서 서비스 디스커버리로, EP21(@HttpExchange)에서 선언적 클라이언트로,
 *   EP23(CircuitBreaker)에서 장애 격리로 단계적으로 개선한다.
 */
@Component
public class JobClient {

    private final RestClient restClient;

    public JobClient(RestClient.Builder builder, @Value("${devjob.job-service.url}") String jobServiceUrl) {
        this.restClient = builder.baseUrl(jobServiceUrl).build();
    }

    public JobInfo getJob(Long jobId) {
        try {
            ApiResponse<JobInfo> response = restClient.get()
                    .uri("/api/jobs/{id}", jobId)
                    .retrieve()
                    .body(new org.springframework.core.ParameterizedTypeReference<ApiResponse<JobInfo>>() {});

            if (response == null || response.data() == null) {
                throw new BusinessException(ErrorCode.JOB_NOT_FOUND);
            }
            return response.data();
        } catch (RestClientException e) {
            throw new BusinessException(ErrorCode.JOB_SERVICE_UNAVAILABLE);
        }
    }
}
