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

import com.arms.api.admin.backup.model.dto.BackupExecutionDTO;
import com.arms.api.admin.backup.model.dto.BackupRequestDTO;
import com.arms.api.admin.backup.model.vo.BackupResponseVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

@Service
@Slf4j
@RequiredArgsConstructor
public class IndexBackupServiceImpl implements IndexBackupService {

    private final IndexBackupAsyncService indexBackupAsyncService;

    @Value("${backup.directory:/mnt}")
    private String backupDirectory;

    @Override
    public BackupResponseVO startBackup(BackupRequestDTO backupRequestDTO) {
        String jobId = UUID.randomUUID().toString().substring(0, 8);
        String datePath = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String timePart = java.time.LocalTime.now().format(DateTimeFormatter.ofPattern("HHmmss"));
        Path outputPath = Paths.get(backupDirectory, datePath, timePart + "_" + backupRequestDTO.getIndexPattern() + "_" + jobId);

        BackupExecutionDTO backupExecutionDTO = new BackupExecutionDTO();
        backupExecutionDTO.setJobId(jobId);
        backupExecutionDTO.setIndexPattern(backupRequestDTO.getIndexPattern());
        backupExecutionDTO.setScrollTimeout(backupRequestDTO.getScrollTimeout());
        backupExecutionDTO.setOutputPath(outputPath);
        backupExecutionDTO.setIncludeCurrentMonth(true);
        backupExecutionDTO.setIncludeMergedIndex(true);

        indexBackupAsyncService.executeBackupWithVerify(backupExecutionDTO); // 이미 @Async

        return BackupResponseVO.builder()
                .jobId(jobId)
                .backupPath(String.valueOf(outputPath))
                .message("백업이 시작되었습니다. 로그에서 진행상황을 확인하세요.")
                .build();
    }
}