package com.zioinfo.mes.spec;

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

import java.util.List;

/**
 * 검사기준/규격 API (QMS 기준정보). 조회 Viewer+, 등록/수정/삭제 Manager+(기준정보).
 */
@RestController
@RequestMapping("/api/mes/specs")
@RequiredArgsConstructor
public class SpecController {

    private final SpecMapper mapper;
    private final AuditService audit;

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

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

    @PostMapping
    public ApiResponse<MesSpec> create(@RequestBody MesSpec s, Authentication auth) {
        AuthSupport.requireManager(auth);
        if (s.getSpecCode() == null || s.getSpecCode().isBlank())
            throw new IllegalArgumentException("ERR-SPEC-400: specCode 필수");
        if (mapper.countByCode(s.getSpecCode(), null) > 0)
            throw new RuntimeException("ERR-SPEC-409: 중복 규격코드");
        if (s.getStatus() == null) s.setStatus("ACTIVE");
        s.setCreatedBy(AuthSupport.actor(auth));
        mapper.insert(s);
        audit.log("SPEC_CREATE", s.getSpecCode(), "item=" + s.getItemCode());
        return ApiResponse.ok(mapper.findById(s.getId()));
    }

    @PutMapping("/{id}")
    public ApiResponse<MesSpec> update(@PathVariable Long id, @RequestBody MesSpec s, Authentication auth) {
        AuthSupport.requireManager(auth);
        MesSpec cur = mapper.findById(id);
        if (cur == null) throw new RuntimeException("ERR-SPEC-404: 규격 없음");
        s.setId(id);
        s.setSpecCode(cur.getSpecCode());
        if (s.getStatus() == null) s.setStatus(cur.getStatus());
        mapper.update(s);
        audit.log("SPEC_UPDATE", cur.getSpecCode(), "id=" + id);
        return ApiResponse.ok(mapper.findById(id));
    }

    @DeleteMapping("/{id}")
    public ApiResponse<Void> delete(@PathVariable Long id, Authentication auth) {
        AuthSupport.requireManager(auth);
        MesSpec cur = mapper.findById(id);
        if (cur == null) throw new RuntimeException("ERR-SPEC-404: 규격 없음");
        mapper.delete(id);
        audit.log("SPEC_DELETE", cur.getSpecCode(), "");
        return ApiResponse.ok(null);
    }
}
