package com.zioinfo.mes.item;

import com.zioinfo.mes.admin.AuditService;
import com.zioinfo.mes.item.mapper.ItemMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Set;

/**
 * 품목 마스터 서비스 — 기준정보(MANAGER+ 가드는 SecurityConfig + 컨트롤러 역할 확인 병행).
 */
@Service
@RequiredArgsConstructor
public class ItemService {

    private static final Set<String> TYPES = Set.of("RAW", "WIP", "FG", "SUB");
    private final ItemMapper mapper;
    private final AuditService audit;

    public List<MesItem> list(String itemType, String status, String keyword) {
        return mapper.findAll(itemType, status, keyword);
    }

    public MesItem get(Long id) {
        MesItem i = mapper.findById(id);
        if (i == null) throw new RuntimeException("ERR-ITEM-404: 품목 없음");
        return i;
    }

    public MesItem create(MesItem item, String actor) {
        validate(item);
        if (mapper.countByCode(item.getItemCode(), null) > 0) {
            throw new RuntimeException("ERR-ITEM-409: 중복 품목코드");
        }
        if (item.getStatus() == null) item.setStatus("ACTIVE");
        item.setCreatedBy(actor);
        mapper.insert(item);
        audit.log("ITEM_CREATE", item.getItemCode(), "type=" + item.getItemType());
        return mapper.findById(item.getId());
    }

    public MesItem update(Long id, MesItem item, String actor) {
        MesItem cur = get(id);
        validate(item);
        if (mapper.countByCode(item.getItemCode(), id) > 0) {
            throw new RuntimeException("ERR-ITEM-409: 중복 품목코드");
        }
        item.setId(id);
        mapper.update(item);
        audit.log("ITEM_UPDATE", cur.getItemCode(), "id=" + id);
        return mapper.findById(id);
    }

    public void delete(Long id) {
        MesItem cur = get(id);
        mapper.delete(id);
        audit.log("ITEM_DELETE", cur.getItemCode(), "id=" + id);
    }

    private void validate(MesItem item) {
        if (item.getItemCode() == null || item.getItemCode().isBlank())
            throw new IllegalArgumentException("ERR-ITEM-400: itemCode 필수");
        if (item.getItemName() == null || item.getItemName().isBlank())
            throw new IllegalArgumentException("ERR-ITEM-400: itemName 필수");
        if (item.getItemType() != null && !TYPES.contains(item.getItemType()))
            throw new IllegalArgumentException("ERR-ITEM-400: itemType 은 RAW/WIP/FG/SUB");
    }
}
