package com.zioinfo.mes.warehouse;

import com.zioinfo.mes.admin.AuditService;
import com.zioinfo.mes.common.ApiResponse;
import com.zioinfo.mes.common.AuthSupport;
import com.zioinfo.mes.warehouse.mapper.WarehouseMapper;
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/warehouses")
@RequiredArgsConstructor
public class WarehouseController {

    private final WarehouseMapper mapper;
    private final AuditService audit;

    @GetMapping
    public ApiResponse<List<MesWarehouse>> list(@RequestParam(required = false) String status) {
        return ApiResponse.ok(mapper.findAll(status));
    }

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

    @PostMapping
    public ApiResponse<MesWarehouse> create(@RequestBody MesWarehouse w, Authentication auth) {
        AuthSupport.requireManager(auth);
        if (w.getWarehouseCode() == null) throw new IllegalArgumentException("ERR-WH-400: warehouseCode 필수");
        if (mapper.countByCode(w.getWarehouseCode(), null) > 0)
            throw new RuntimeException("ERR-WH-409: 중복 창고코드");
        if (w.getStatus() == null) w.setStatus("ACTIVE");
        w.setCreatedBy(AuthSupport.actor(auth));
        mapper.insert(w);
        audit.log("WAREHOUSE_CREATE", w.getWarehouseCode(), "");
        return ApiResponse.ok(mapper.findById(w.getId()));
    }

    @PutMapping("/{id}")
    public ApiResponse<MesWarehouse> update(@PathVariable Long id, @RequestBody MesWarehouse w, Authentication auth) {
        AuthSupport.requireManager(auth);
        require(id);
        w.setId(id);
        mapper.update(w);
        audit.log("WAREHOUSE_UPDATE", w.getWarehouseCode(), "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("WAREHOUSE_DELETE", String.valueOf(id), "");
        return ApiResponse.ok(null);
    }

    // ── locations / bins ──
    @GetMapping("/{warehouseCode}/locations")
    public ApiResponse<List<MesLocation>> locations(@PathVariable String warehouseCode) {
        return ApiResponse.ok(mapper.findLocations(warehouseCode));
    }

    @PostMapping("/locations")
    public ApiResponse<MesLocation> addLocation(@RequestBody MesLocation l, Authentication auth) {
        AuthSupport.requireManager(auth);
        if (l.getWarehouseCode() == null || l.getLocationCode() == null)
            throw new IllegalArgumentException("ERR-WH-400: warehouseCode/locationCode 필수");
        if (l.getStatus() == null) l.setStatus("ACTIVE");
        mapper.insertLocation(l);
        audit.log("LOCATION_CREATE", l.getWarehouseCode(), "loc=" + l.getLocationCode());
        return ApiResponse.ok(l);
    }

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

    private MesWarehouse require(Long id) {
        MesWarehouse w = mapper.findById(id);
        if (w == null) throw new RuntimeException("ERR-WH-404: 창고 없음");
        return w;
    }
}
