package com.ga.api.controller.batch;

import com.ga.common.annotation.RequirePermission;
import com.ga.common.exception.BizException;
import com.ga.common.exception.ErrorCode;
import com.ga.common.model.ApiResponse;
import com.ga.core.mapper.settle.BatchJobLogMapper;
import com.ga.core.vo.settle.BatchJobLogVO;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * 배치 트리거 — 실제 배치 잡 실행은 ga-batch 모듈의 별도 Spring Boot 프로세스에서 수행.
 * ga-api 에서는 batch_job_log 만 조회/요청 등록.
 *
 * 운영 환경에서는 메시지 큐(Kafka, Redis Streams) 또는
 * Spring Batch JobLauncher REST API 로 ga-batch 프로세스를 호출하는 것을 권장.
 */
@Slf4j
@Tag(name = "배치")
@RestController
@RequestMapping("/api/batch")
@RequiredArgsConstructor
public class BatchTriggerController {

    private final BatchJobLogMapper jobLogMapper;

    /** 정산 배치 시작 요청 (실제 실행은 ga-batch 프로세스가 폴링/큐) */
    @PostMapping("/settlement/run")
    @RequirePermission(menu = "BATCH_RUN", perm = "APPROVE")
    public ApiResponse<Long> runSettlement(@RequestBody Map<String, String> body) {
        String settleMonth = body.get("settleMonth");
        if (settleMonth == null || !settleMonth.matches("\\d{6}")) {
            throw new BizException(ErrorCode.INVALID_PARAMETER, "settleMonth (yyyyMM) 가 필요합니다");
        }
        if (jobLogMapper.isRunning("MONTHLY_SETTLEMENT") > 0) {
            throw new BizException(ErrorCode.BATCH_RUNNING);
        }
        BatchJobLogVO log = new BatchJobLogVO();
        log.setJobName("MONTHLY_SETTLEMENT");
        log.setSettleMonth(settleMonth);
        log.setStatus("REQUESTED");
        log.setTriggeredBy(com.ga.common.util.SecurityUtil.getCurrentUserId());
        jobLogMapper.insert(log);
        return ApiResponse.ok(log.getJobId());
    }

    @GetMapping("/status")
    @RequirePermission(menu = "BATCH_RUN", perm = "READ")
    public ApiResponse<BatchJobLogVO> latest(@RequestParam(defaultValue = "MONTHLY_SETTLEMENT") String jobName) {
        return ApiResponse.ok(jobLogMapper.selectLatest(jobName));
    }

    @GetMapping("/jobs")
    @RequirePermission(menu = "BATCH_RUN", perm = "READ")
    public ApiResponse<List<BatchJobLogVO>> list(@RequestParam(required = false) String jobName,
                                                  @RequestParam(required = false) String settleMonth) {
        return ApiResponse.ok(jobLogMapper.selectList(jobName, settleMonth));
    }

    @GetMapping("/jobs/{jobId}")
    @RequirePermission(menu = "BATCH_RUN", perm = "READ")
    public ApiResponse<BatchJobLogVO> detail(@PathVariable Long jobId) {
        return ApiResponse.ok(jobLogMapper.selectById(jobId));
    }
}
