package com.arms.api.admin.restore.service;

import com.arms.api.admin.restore.model.dto.RestoreExecutionDTO;
import com.arms.api.admin.restore.model.dto.RestoreRequestDTO;
import com.arms.api.admin.restore.model.vo.RestoreResponseVO;
import com.arms.api.admin.restore.model.vo.RestoreVerifyResultVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.CompletableFuture;

@Service
@Slf4j
@RequiredArgsConstructor
public class IndexRestoreServiceImpl implements IndexRestoreService {

    private final IndexRestoreAsyncService indexRestoreAsyncService;

    @Override
    public RestoreResponseVO startRestore(RestoreRequestDTO restoreRequestDTO) {
        String jobId = UUID.randomUUID().toString().substring(0, 8);

        RestoreExecutionDTO restoreExecutionDTO = new RestoreExecutionDTO();
        restoreExecutionDTO.setJobId(jobId);
        restoreExecutionDTO.setBackupFilePath(restoreRequestDTO.getBackupFilePath());
        restoreExecutionDTO.setTargetIndexName(restoreRequestDTO.getTargetIndexName());

        CompletableFuture<RestoreVerifyResultVO> future = indexRestoreAsyncService.executeRestoreWithVerify(restoreExecutionDTO);

        future.thenAccept(result -> {
            if (result.isVerified()) {
                log.info("[복구 검증 성공] jobId: {}, 백업: {}, 복구: {}",
                        jobId, result.getBackupDocCount(), result.getRestoredDocCount());
            } else {
                log.error("[복구 검증 실패] jobId: {}, message: {}", jobId, result.getMessage());
            }
        }).exceptionally(e -> {
            log.error("[복구 실패] jobId: {}, error: {}", jobId, e.getMessage(), e);
            return null;
        });

        return RestoreResponseVO.builder()
                .jobId(jobId)
                .backupPath(restoreRequestDTO.getBackupFilePath())
                .message("복구가 시작되었습니다. 로그에서 진행상황을 확인하세요.")
                .build();
    }
}