package com.zioinfo.mes.bom;

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;
import java.util.Map;

/**
 * BOM API — 구성 CRUD + 트리 전개 + 소요량(MRP). 조회 Viewer+, 변경 Manager+.
 */
@RestController
@RequestMapping("/api/mes/bom")
@RequiredArgsConstructor
public class BomController {

    private final BomService service;

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

    @GetMapping("/parent/{parentItemCode}")
    public ApiResponse<List<MesBom>> byParent(@PathVariable String parentItemCode,
                                              @RequestParam(required = false) String bomVersion) {
        return ApiResponse.ok(service.listByParent(parentItemCode, bomVersion));
    }

    /** 다단 BOM 트리 전개. */
    @GetMapping("/explode/{parentItemCode}")
    public ApiResponse<Map<String, Object>> explode(@PathVariable String parentItemCode,
                                                    @RequestParam(defaultValue = "1") double qty,
                                                    @RequestParam(required = false) String bomVersion) {
        return ApiResponse.ok(service.explode(parentItemCode, qty, bomVersion));
    }

    /** 소요량 집계(MRP) — 리프 자재별 총 소요량. */
    @GetMapping("/requirement/{parentItemCode}")
    public ApiResponse<Map<String, Double>> requirement(@PathVariable String parentItemCode,
                                                       @RequestParam(defaultValue = "1") double qty,
                                                       @RequestParam(required = false) String bomVersion) {
        return ApiResponse.ok(service.materialRequirement(parentItemCode, qty, bomVersion));
    }

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

    @PutMapping("/{id}")
    public ApiResponse<MesBom> update(@PathVariable Long id, @RequestBody MesBom bom, Authentication auth) {
        AuthSupport.requireManager(auth);
        return ApiResponse.ok(service.update(id, bom, AuthSupport.actor(auth)));
    }

    @DeleteMapping("/{id}")
    public ApiResponse<Void> delete(@PathVariable Long id, Authentication auth) {
        AuthSupport.requireManager(auth);
        service.delete(id);
        return ApiResponse.ok(null);
    }
}
