package com.zioinfo.mes.lotserial;

import com.zioinfo.mes.admin.AuditService;
import com.zioinfo.mes.common.ApiResponse;
import com.zioinfo.mes.common.AuthSupport;
import com.zioinfo.mes.lotserial.mapper.LotSerialMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * LOT/시리얼 관리 API (WMS). 조회 Viewer+, 등록/상태변경 Worker+.
 */
@RestController
@RequestMapping("/api/mes/lotserial")
@RequiredArgsConstructor
public class LotSerialController {

    private final LotSerialMapper mapper;
    private final AuditService audit;

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

    @GetMapping("/{id}")
    public ApiResponse<MesLotSerial> get(@PathVariable Long id) {
        MesLotSerial l = mapper.findById(id);
        if (l == null) throw new RuntimeException("ERR-LOT-404: LOT 없음");
        return ApiResponse.ok(l);
    }

    /** 유효기간 임박 LOT(days 이내, 기본 30일). */
    @GetMapping("/expiring")
    public ApiResponse<List<MesLotSerial>> expiring(@RequestParam(defaultValue = "30") int days) {
        return ApiResponse.ok(mapper.findExpiringSoon(days));
    }

    @PostMapping
    public ApiResponse<MesLotSerial> create(@RequestBody MesLotSerial l, Authentication auth) {
        if (l.getLotNo() == null || l.getLotNo().isBlank())
            throw new IllegalArgumentException("ERR-LOT-400: lotNo 필수");
        if (l.getStatus() == null) l.setStatus("ACTIVE");
        l.setCreatedBy(AuthSupport.actor(auth));
        mapper.insert(l);
        audit.log("LOTSERIAL_CREATE", l.getLotNo(), "item=" + l.getItemCode());
        return ApiResponse.ok(mapper.findById(l.getId()));
    }

    @PutMapping("/{id}/status")
    public ApiResponse<MesLotSerial> updateStatus(@PathVariable Long id, @RequestBody StatusRequest req,
                                                  Authentication auth) {
        MesLotSerial l = mapper.findById(id);
        if (l == null) throw new RuntimeException("ERR-LOT-404: LOT 없음");
        mapper.updateStatus(id, req.status());
        audit.log("LOTSERIAL_STATUS", l.getLotNo(), l.getStatus() + " -> " + req.status());
        return ApiResponse.ok(mapper.findById(id));
    }

    record StatusRequest(String status) {}
}
