package com.zioinfo.mes.spc;

import com.zioinfo.mes.common.ApiResponse;
import com.zioinfo.mes.common.AuthSupport;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

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

/**
 * SPC 관리도 API (QMS) — Xbar-R 관리한계·Cp/Cpk·이상감지. 조회 Viewer+, 샘플 적재 Worker+.
 */
@RestController
@RequestMapping("/api/mes/spc")
@RequiredArgsConstructor
public class SpcController {

    private final SpcService service;

    /** 관리도 목록(차트코드). */
    @GetMapping("/charts")
    public ApiResponse<List<String>> charts() {
        return ApiResponse.ok(service.charts());
    }

    /** 부분군 샘플 목록. */
    @GetMapping("/samples")
    public ApiResponse<List<MesSpcSample>> samples(@RequestParam String chartCode,
                                                  @RequestParam(defaultValue = "100") int limit) {
        return ApiResponse.ok(service.samples(chartCode, limit));
    }

    /** 관리도 계산 — Xbar/R 관리한계 + Cp/Cpk(lsl/usl 제공 시) + 이상감지. */
    @GetMapping("/chart")
    public ApiResponse<Map<String, Object>> chart(@RequestParam String chartCode,
                                                 @RequestParam(required = false) Double lsl,
                                                 @RequestParam(required = false) Double usl) {
        return ApiResponse.ok(service.chart(chartCode, lsl, usl));
    }

    /** 부분군 측정값 적재(평균/범위 자동 계산). */
    @PostMapping("/samples")
    public ApiResponse<MesSpcSample> addSample(@RequestBody SampleRequest req, Authentication auth) {
        return ApiResponse.ok(service.addSample(req.chartCode(), req.itemCode(), req.characteristic(),
            req.subgroupNo(), req.values(), AuthSupport.actor(auth)));
    }

    record SampleRequest(String chartCode, String itemCode, String characteristic,
                         Integer subgroupNo, List<Double> values) {}
}
