package com.ga.batch.controller;

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 lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.batch.core.Job;
import org.springframework.batch.core.JobParameters;
import org.springframework.batch.core.JobParametersBuilder;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

/**
 * ga-batch 프로세스 내부 트리거. ga-api 가 HTTP 로 호출.
 */
@Slf4j
@RestController
@RequestMapping("/internal/jobs")
@RequiredArgsConstructor
public class JobLauncherController {

    private final JobLauncher jobLauncher;
    private final Job monthlySettlementJob;
    private final BatchJobLogMapper jobLogMapper;

    @PostMapping("/monthly-settlement")
    public ApiResponse<Long> runMonthlySettlement(@RequestBody Map<String, String> body) throws Exception {
        String settleMonth = body.get("settleMonth");
        if (settleMonth == null || !settleMonth.matches("\\d{6}")) {
            throw new BizException(ErrorCode.INVALID_PARAMETER, "settleMonth (yyyyMM)");
        }

        BatchJobLogVO log = new BatchJobLogVO();
        log.setJobName("MONTHLY_SETTLEMENT");
        log.setSettleMonth(settleMonth);
        log.setStatus("STARTED");
        jobLogMapper.insert(log);

        JobParameters params = new JobParametersBuilder()
                .addString("settleMonth", settleMonth)
                .addLong("jobLogId", log.getJobId())
                .addLong("ts", System.currentTimeMillis())
                .toJobParameters();

        jobLauncher.run(monthlySettlementJob, params);
        return ApiResponse.ok(log.getJobId());
    }
}
