package com.zioinfo.mes.inventory;

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 — 조회/이동(transfer)/조정/이력. 조회 Viewer+, 이동·조정 Worker+.
 */
@RestController
@RequestMapping("/api/mes/inventory")
@RequiredArgsConstructor
public class InventoryController {

    private final InventoryService service;

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

    @GetMapping("/available/{itemCode}")
    public ApiResponse<Double> available(@PathVariable String itemCode) {
        return ApiResponse.ok(service.available(itemCode));
    }

    @GetMapping("/below-safety")
    public ApiResponse<List<MesInventory>> belowSafety() {
        return ApiResponse.ok(service.belowSafety());
    }

    @GetMapping("/txns")
    public ApiResponse<List<MesInventoryTxn>> txns(@RequestParam(required = false) String itemCode,
                                                   @RequestParam(required = false) String refType,
                                                   @RequestParam(required = false) String refNo,
                                                   @RequestParam(defaultValue = "200") int limit) {
        return ApiResponse.ok(service.txns(itemCode, refType, refNo, limit));
    }

    /** 재고 이동(로케이션/창고 간). Worker+. */
    @PostMapping("/transfer")
    public ApiResponse<Void> transfer(@RequestBody TransferRequest req, Authentication auth) {
        service.transfer(req.itemCode(), req.fromWarehouse(), req.fromLocation(),
            req.toWarehouse(), req.toLocation(), req.lotNo(), req.qty(), AuthSupport.actor(auth));
        return ApiResponse.ok(null);
    }

    record TransferRequest(String itemCode, String fromWarehouse, String fromLocation,
                           String toWarehouse, String toLocation, String lotNo, double qty) {}
}
