package com.zioinfo.mes.inspection;

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;

/**
 * 검사 API (QMS) — IQC/IPQC/OQC. 조회 Viewer+, 등록/판정 Worker+.
 */
@RestController
@RequestMapping("/api/mes/inspections")
@RequiredArgsConstructor
public class InspectionController {

    private final InspectionService service;

    @GetMapping
    public ApiResponse<List<MesInspection>> list(@RequestParam(required = false) String inspectionType,
                                                @RequestParam(required = false) String result,
                                                @RequestParam(required = false) String itemCode) {
        return ApiResponse.ok(service.list(inspectionType, result, itemCode));
    }

    @GetMapping("/pass-rate")
    public ApiResponse<List<Map<String, Object>>> passRate(@RequestParam(defaultValue = "30") int days) {
        return ApiResponse.ok(service.passRate(days));
    }

    @GetMapping("/{id}")
    public ApiResponse<MesInspection> get(@PathVariable Long id) {
        return ApiResponse.ok(service.get(id));
    }

    @PostMapping
    public ApiResponse<MesInspection> create(@RequestBody MesInspection i, Authentication auth) {
        return ApiResponse.ok(service.create(i, AuthSupport.actor(auth)));
    }

    /** AI 판정 보조 — 측정값 vs 스펙 자동 판정(FAIL 시 NCR 자동 생성). */
    @PostMapping("/{id}/judge")
    public ApiResponse<Map<String, Object>> judge(@PathVariable Long id, @RequestBody JudgeRequest req,
                                                  Authentication auth) {
        return ApiResponse.ok(service.judge(id, req.measured(), req.lsl(), req.usl(), req.target(),
            req.defectQty(), req.defectCode(), AuthSupport.actor(auth)));
    }

    /** 수동 결과 입력(PASS/FAIL). FAIL 시 NCR 자동 생성. */
    @PostMapping("/{id}/result")
    public ApiResponse<MesInspection> setResult(@PathVariable Long id, @RequestBody ResultRequest req,
                                               Authentication auth) {
        return ApiResponse.ok(service.setResult(id, req.result(), req.defectQty(), req.defectCode(),
            AuthSupport.actor(auth)));
    }

    record JudgeRequest(double measured, Double lsl, Double usl, Double target,
                        double defectQty, String defectCode) {}
    record ResultRequest(String result, double defectQty, String defectCode) {}
}
