package com.zioinfo.mes.ncr;

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;

/**
 * 부적합(NCR) API (QMS). 조회 Viewer+, 등록/처리 Worker+, CAPA 연계 Worker+.
 */
@RestController
@RequestMapping("/api/mes/ncr")
@RequiredArgsConstructor
public class NcrController {

    private final NcrService service;

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

    @GetMapping("/board")
    public ApiResponse<List<Map<String, Object>>> board() {
        return ApiResponse.ok(service.statusBoard());
    }

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

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

    @PostMapping("/{id}/disposition")
    public ApiResponse<MesNcr> disposition(@PathVariable Long id, @RequestBody DispositionRequest req,
                                          Authentication auth) {
        return ApiResponse.ok(service.disposition(id, req.disposition(), AuthSupport.actor(auth)));
    }

    @PostMapping("/{id}/transition")
    public ApiResponse<MesNcr> transition(@PathVariable Long id, @RequestBody StatusRequest req,
                                         Authentication auth) {
        return ApiResponse.ok(service.transition(id, req.status(), AuthSupport.actor(auth)));
    }

    @PostMapping("/{id}/link-capa")
    public ApiResponse<Void> linkCapa(@PathVariable Long id, @RequestBody CapaLinkRequest req,
                                     Authentication auth) {
        service.linkCapa(id, req.capaId(), AuthSupport.actor(auth));
        return ApiResponse.ok(null);
    }

    record DispositionRequest(String disposition) {}
    record StatusRequest(String status) {}
    record CapaLinkRequest(Long capaId) {}
}
