package com.zioinfo.esn.service;

import com.zioinfo.esn.domain.TagBindingVo;
import com.zioinfo.esn.domain.UpdateQueueVo;
import com.zioinfo.esn.mapper.TagBindingMapper;
import com.zioinfo.esn.mapper.UpdateQueueMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

@Service
@RequiredArgsConstructor
public class TagBindingService {
    private final TagBindingMapper bindingMapper;
    private final UpdateQueueMapper queueMapper;

    public List<TagBindingVo> list(String tenantCode, Long storeId,
                                   String bindStatus, String keyword) {
        return bindingMapper.findAll(tenantCode, storeId, bindStatus, keyword);
    }

    public TagBindingVo get(Long id) { return bindingMapper.findById(id); }

    public TagBindingVo getByDeviceId(String deviceId) {
        return bindingMapper.findByDeviceId(deviceId);
    }

    @Transactional
    public TagBindingVo bind(TagBindingVo vo) {
        // 기존 바인딩이 있으면 해제 후 재바인딩
        TagBindingVo existing = bindingMapper.findByDeviceId(vo.getDeviceId());
        if (existing != null) {
            bindingMapper.unbind(existing.getId());
        }
        bindingMapper.insert(vo);
        return bindingMapper.findById(vo.getId());
    }

    @Transactional
    public void unbind(Long id) {
        bindingMapper.unbind(id);
    }

    /**
     * 가격 변경 시 해당 상품에 바인딩된 모든 태그에 업데이트 큐 생성
     * POS 가격변경 → 이 메서드 → e-paper 태그들에게 전파
     */
    @Transactional
    public int enqueueByProductCode(String tenantCode, Long storeId,
                                    String productCode, java.math.BigDecimal newPrice,
                                    java.math.BigDecimal newSalePrice, Long posCvtId) {
        List<TagBindingVo> bindings = bindingMapper.findByProductCode(tenantCode, storeId, productCode);
        for (TagBindingVo b : bindings) {
            UpdateQueueVo q = new UpdateQueueVo();
            q.setTenantCode(tenantCode);
            q.setStoreId(storeId);
            q.setBindingId(b.getId());
            q.setDeviceId(b.getDeviceId());
            q.setProductCode(productCode);
            q.setNewPrice(newPrice);
            q.setNewSalePrice(newSalePrice);
            q.setTemplateCode(b.getTemplateCode());
            q.setPriority(5);
            q.setPosCvtId(posCvtId);
            queueMapper.insert(q);
        }
        return bindings.size();
    }
}
