package com.zioinfo.mes.routing;

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

import java.util.List;

/**
 * 라우팅(공정순서·표준시간) API. 조회 Viewer+, 변경 Manager+.
 */
@RestController
@RequestMapping("/api/mes/routings")
@RequiredArgsConstructor
public class RoutingController {

    private final RoutingMapper mapper;
    private final AuditService audit;

    @GetMapping
    public ApiResponse<List<MesRouting>> list(@RequestParam(required = false) String itemCode) {
        return ApiResponse.ok(itemCode != null ? mapper.findByItem(itemCode) : mapper.findAll());
    }

    @GetMapping("/{id}")
    public ApiResponse<MesRouting> get(@PathVariable Long id) {
        MesRouting r = mapper.findById(id);
        if (r == null) throw new RuntimeException("ERR-ROUTING-404: 라우팅 없음");
        return ApiResponse.ok(r);
    }

    @PostMapping
    public ApiResponse<MesRouting> create(@RequestBody MesRouting r, Authentication auth) {
        AuthSupport.requireManager(auth);
        if (r.getItemCode() == null) throw new IllegalArgumentException("ERR-ROUTING-400: itemCode 필수");
        if (r.getStatus() == null) r.setStatus("ACTIVE");
        r.setCreatedBy(AuthSupport.actor(auth));
        mapper.insert(r);
        audit.log("ROUTING_CREATE", r.getItemCode(), "op=" + r.getOpSeq());
        return ApiResponse.ok(mapper.findById(r.getId()));
    }

    @PutMapping("/{id}")
    public ApiResponse<MesRouting> update(@PathVariable Long id, @RequestBody MesRouting r, Authentication auth) {
        AuthSupport.requireManager(auth);
        r.setId(id);
        mapper.update(r);
        audit.log("ROUTING_UPDATE", r.getItemCode(), "id=" + id);
        return ApiResponse.ok(mapper.findById(id));
    }

    @DeleteMapping("/{id}")
    public ApiResponse<Void> delete(@PathVariable Long id, Authentication auth) {
        AuthSupport.requireManager(auth);
        mapper.delete(id);
        audit.log("ROUTING_DELETE", String.valueOf(id), "");
        return ApiResponse.ok(null);
    }
}
