package com.zioinfo.mall.inventory;

import com.zioinfo.mall.common.ApiResponse;
import com.zioinfo.mall.integration.ErpClient;
import com.zioinfo.mall.inventory.mapper.InventoryMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/** 재고 API — /api/mall/inventory. 조회/변경 MANAGER+. ERP 동기화 연계. */
@RestController
@RequestMapping("/api/mall/inventory")
@RequiredArgsConstructor
@PreAuthorize("hasAnyRole('ADMIN','MANAGER')")
public class InventoryController {

    private final InventoryMapper mapper;
    private final ErpClient erpClient;

    @GetMapping
    public ApiResponse<List<MallInventory>> list(@RequestParam(required = false) Boolean lowStock) {
        return ApiResponse.ok(mapper.findAll(lowStock));
    }

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

    @PostMapping
    public ApiResponse<MallInventory> create(@RequestBody MallInventory inv) {
        mapper.insert(inv);
        return ApiResponse.ok(mapper.findById(inv.getId()));
    }

    @PutMapping("/{id}/adjust")
    public ApiResponse<MallInventory> adjust(@PathVariable Long id, @RequestBody Map<String, Integer> req) {
        mapper.adjust(id, req.getOrDefault("delta", 0));
        return ApiResponse.ok(mapper.findById(id));
    }

    /** ERP 재고 동기화 — ErpClient.getStock(sku) 결과 반영. 실패 시 PENDING 유지. */
    @PostMapping("/{id}/erp-sync")
    public ApiResponse<MallInventory> erpSync(@PathVariable Long id) {
        MallInventory inv = mapper.findById(id);
        if (inv == null) throw new RuntimeException("ERR-INV-404: 재고 정보 없음");
        Map<String, Object> erp = erpClient.getStock(inv.getSku());
        Object qty = erp.get("onHand");
        if (qty == null) qty = erp.get("quantity");
        if (qty != null) {
            mapper.setErpSync(id, "SYNCED", ((Number) qty).intValue());
        } else {
            mapper.setErpSync(id, "PENDING", null);
        }
        return ApiResponse.ok(mapper.findById(id));
    }
}
