package com.kt.ai.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.kt.ai.exception.JobNotFoundException;
import com.kt.ai.model.dto.response.JobStatusResponse;
import com.kt.ai.model.enums.JobStatus;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * Job 상태 관리 서비스
 *
 * @author AI Service Team
 * @since 1.0.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class JobStatusService {

    private final CacheService cacheService;
    private final ObjectMapper objectMapper;

    /**
     * Job 상태 조회
     */
    public JobStatusResponse getJobStatus(String jobId) {
        Object cached = cacheService.getJobStatus(jobId);
        if (cached == null) {
            throw new JobNotFoundException(jobId);
        }

        return objectMapper.convertValue(cached, JobStatusResponse.class);
    }

    /**
     * Job 상태 업데이트
     */
    public void updateJobStatus(String jobId, JobStatus status, String message) {
        JobStatusResponse response = JobStatusResponse.builder()
                .jobId(jobId)
                .status(status)
                .progress(calculateProgress(status))
                .message(message)
                .createdAt(LocalDateTime.now())
                .build();

        cacheService.saveJobStatus(jobId, response);
        log.info("Job 상태 업데이트: jobId={}, status={}", jobId, status);
    }

    private int calculateProgress(JobStatus status) {
        return switch (status) {
            case PENDING -> 0;
            case PROCESSING -> 50;
            case COMPLETED -> 100;
            case FAILED -> 0;
        };
    }
}
