package com.zioinfo.mes.process;

import com.zioinfo.mes.admin.AuditService;
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;

/**
 * 공정 진행/작업자 배정 API (ProcessBoard 칸반용). 조회 Viewer+, 진행 입력 Worker+.
 */
@RestController
@RequestMapping("/api/mes/process")
@RequiredArgsConstructor
public class ProcessController {

    private final ProcessMapper mapper;
    private final AuditService audit;

    @GetMapping("/workorder/{workorderId}")
    public ApiResponse<List<MesProcessProgress>> byWorkorder(@PathVariable Long workorderId) {
        return ApiResponse.ok(mapper.findByWorkorder(workorderId));
    }

    /** 실시간 진행 중 공정(칸반 RUNNING 칼럼). */
    @GetMapping("/running")
    public ApiResponse<List<MesProcessProgress>> running() {
        return ApiResponse.ok(mapper.findRunning());
    }

    @PostMapping
    public ApiResponse<MesProcessProgress> create(@RequestBody MesProcessProgress p, Authentication auth) {
        if (p.getWorkorderId() == null) throw new IllegalArgumentException("ERR-PROC-400: workorderId 필수");
        if (p.getStatus() == null) p.setStatus("WAITING");
        mapper.insert(p);
        audit.log("PROCESS_CREATE", p.getWoNo(), "op=" + p.getOpSeq());
        return ApiResponse.ok(mapper.findById(p.getId()));
    }

    /** 공정 상태 전이 — WAITING→RUNNING→DONE. Worker+. */
    @PutMapping("/{id}/status")
    public ApiResponse<MesProcessProgress> status(@PathVariable Long id, @RequestBody StatusRequest req) {
        MesProcessProgress cur = mapper.findById(id);
        if (cur == null) throw new RuntimeException("ERR-PROC-404: 공정 진행 없음");
        mapper.updateStatus(id, req.status());
        audit.log("PROCESS_STATUS", cur.getWoNo(), cur.getStatus() + " -> " + req.status());
        return ApiResponse.ok(mapper.findById(id));
    }

    @PutMapping("/{id}")
    public ApiResponse<MesProcessProgress> update(@PathVariable Long id, @RequestBody MesProcessProgress p, Authentication auth) {
        p.setId(id);
        mapper.update(p);
        return ApiResponse.ok(mapper.findById(id));
    }

    record StatusRequest(String status) {}
}
