package com.zioinfo.mes.certificate;

import com.zioinfo.mes.admin.AuditService;
import com.zioinfo.mes.certificate.mapper.CertificateMapper;
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.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.List;

/**
 * 성적서/MSDS API (QMS). 조회 Viewer+, 발행 Worker+.
 */
@RestController
@RequestMapping("/api/mes/certificates")
@RequiredArgsConstructor
public class CertificateController {

    private final CertificateMapper mapper;
    private final AuditService audit;

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

    @GetMapping("/{id}")
    public ApiResponse<MesCertificate> get(@PathVariable Long id) {
        MesCertificate c = mapper.findById(id);
        if (c == null) throw new RuntimeException("ERR-CERT-404: 성적서 없음");
        return ApiResponse.ok(c);
    }

    @PostMapping
    public ApiResponse<MesCertificate> create(@RequestBody MesCertificate c, Authentication auth) {
        if (c.getCertType() == null) c.setCertType("COA");
        if (c.getCertificateNo() == null || c.getCertificateNo().isBlank())
            c.setCertificateNo(c.getCertType() + "-" + LocalDate.now().format(DateTimeFormatter.BASIC_ISO_DATE)
                + "-" + (System.currentTimeMillis() % 100000));
        if (mapper.countByNo(c.getCertificateNo()) > 0)
            throw new RuntimeException("ERR-CERT-409: 중복 성적서번호");
        if (c.getIssuedDate() == null) c.setIssuedDate(LocalDate.now());
        if (c.getStatus() == null) c.setStatus("ISSUED");
        c.setCreatedBy(AuthSupport.actor(auth));
        mapper.insert(c);
        audit.log("CERTIFICATE_ISSUE", c.getCertificateNo(), "type=" + c.getCertType() + " item=" + c.getItemCode());
        return ApiResponse.ok(mapper.findById(c.getId()));
    }
}
