package com.zioinfo.mes.capa;

import com.zioinfo.mes.admin.AuditService;
import com.zioinfo.mes.capa.mapper.CapaMapper;
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.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 시정·예방조치(CAPA) API (QMS). 조회 Viewer+, 등록/수정/상태전이 Worker+.
 */
@RestController
@RequestMapping("/api/mes/capa")
@RequiredArgsConstructor
public class CapaController {

    private final CapaMapper mapper;
    private final AuditService audit;

    @GetMapping
    public ApiResponse<List<MesCapa>> list(@RequestParam(required = false) String status,
                                          @RequestParam(required = false) String capaType) {
        return ApiResponse.ok(mapper.findAll(status, capaType));
    }

    @GetMapping("/{id}")
    public ApiResponse<MesCapa> get(@PathVariable Long id) {
        MesCapa c = mapper.findById(id);
        if (c == null) throw new RuntimeException("ERR-CAPA-404: CAPA 없음");
        return ApiResponse.ok(c);
    }

    @PostMapping
    public ApiResponse<MesCapa> create(@RequestBody MesCapa c, Authentication auth) {
        if (c.getCapaNo() == null || c.getCapaNo().isBlank())
            c.setCapaNo("CAPA-" + LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE)
                + "-" + (System.currentTimeMillis() % 100000));
        if (c.getCapaType() == null) c.setCapaType("CORRECTIVE");
        c.setStatus("OPEN");
        c.setCreatedBy(AuthSupport.actor(auth));
        mapper.insert(c);
        audit.log("CAPA_CREATE", c.getCapaNo(), "ncr=" + c.getNcrNo());
        return ApiResponse.ok(mapper.findById(c.getId()));
    }

    @PutMapping("/{id}")
    public ApiResponse<MesCapa> update(@PathVariable Long id, @RequestBody MesCapa c, Authentication auth) {
        MesCapa cur = mapper.findById(id);
        if (cur == null) throw new RuntimeException("ERR-CAPA-404: CAPA 없음");
        c.setId(id);
        mapper.update(c);
        audit.log("CAPA_UPDATE", cur.getCapaNo(), "id=" + id);
        return ApiResponse.ok(mapper.findById(id));
    }

    /** 상태 전이(OPEN/INPROGRESS/VERIFY/CLOSED). CLOSE 시 effectiveness 권장. */
    @PostMapping("/{id}/transition")
    public ApiResponse<MesCapa> transition(@PathVariable Long id, @RequestBody TransitionRequest req,
                                          Authentication auth) {
        MesCapa cur = mapper.findById(id);
        if (cur == null) throw new RuntimeException("ERR-CAPA-404: CAPA 없음");
        mapper.updateStatus(id, req.status(), req.effectiveness());
        audit.log("CAPA_STATUS", cur.getCapaNo(), cur.getStatus() + " -> " + req.status());
        return ApiResponse.ok(mapper.findById(id));
    }

    record TransitionRequest(String status, String effectiveness) {}
}
