package com.zioinfo.mes.receiving;

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 (WMS). 조회 Viewer+, 등록/검수 Worker+, 입고확정(재고증가) Worker+.
 */
@RestController
@RequestMapping("/api/mes/receiving")
@RequiredArgsConstructor
public class ReceivingController {

    private final ReceivingService service;

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

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

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

    /** 입고확정 — 재고 증가. */
    @PostMapping("/{id}/accept")
    public ApiResponse<MesReceiving> accept(@PathVariable Long id, @RequestBody(required = false) AcceptRequest req,
                                           Authentication auth) {
        String result = req == null ? null : req.inspectionResult();
        return ApiResponse.ok(service.accept(id, result, AuthSupport.actor(auth)));
    }

    @PostMapping("/{id}/reject")
    public ApiResponse<MesReceiving> reject(@PathVariable Long id, @RequestBody(required = false) RejectRequest req,
                                           Authentication auth) {
        String reason = req == null ? null : req.reason();
        return ApiResponse.ok(service.reject(id, reason, AuthSupport.actor(auth)));
    }

    record AcceptRequest(String inspectionResult) {}
    record RejectRequest(String reason) {}
}
