package com.zioinfo.esn.service;

import com.zioinfo.esn.domain.PosCvtVo;
import com.zioinfo.esn.mapper.PosCvtMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Slf4j
@Service
@RequiredArgsConstructor
public class PosCvtService {
    private final PosCvtMapper mapper;
    private final TagBindingService tagBindingService;

    public List<PosCvtVo> list(String tenantCode, Long storeId, String status, String keyword) {
        return mapper.findAll(tenantCode, storeId, status, keyword);
    }

    public PosCvtVo get(Long id) { return mapper.findById(id); }

    /**
     * POS 가격변경 처리 → 바인딩된 e-paper 태그에 업데이트 큐 자동 생성
     */
    @Transactional
    public int process(Long id) {
        PosCvtVo pos = mapper.findById(id);
        if (pos == null) return 0;

        mapper.updateStatus(id, "PROCESSED", null);

        // 이 상품에 바인딩된 e-paper 태그들에 가격 업데이트 큐 생성
        int queued = tagBindingService.enqueueByProductCode(
            pos.getTenantCode(), pos.getStoreId(),
            pos.getProductCode(), pos.getPrice(), pos.getSalePrice(), id);

        log.info("POS 처리 완료: posCvtId={}, product={}, 큐생성={}개",
            id, pos.getProductCode(), queued);
        return queued;
    }

    public void markError(Long id, String errorMessage) {
        mapper.updateStatus(id, "ERROR", errorMessage);
    }

    public void ignore(Long id) {
        mapper.updateStatus(id, "IGNORED", null);
    }
}
