package com.jeesharp.business.modules.coupon.service.impl;

import com.jeesharp.business.modules.coupon.entity.CouponTemplate;
import com.jeesharp.business.modules.coupon.mapper.CouponTemplateMapper;
import com.jeesharp.business.modules.coupon.service.CouponTemplateService;
import com.jeesharp.business.modules.coupon.vo.CouponTemplateQueryVO;
import com.jeesharp.framework.exception.BizErrorException;
import com.jeesharp.framework.mybatis.core.service.CrudService;
import cn.hutool.core.util.StrUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 优惠券模板领域服务实现。
 *
 * @author jeesharp
 * @since 2026-05-07
 */
@Service
@Transactional(readOnly = true)
public class CouponTemplateServiceImpl extends CrudService<CouponTemplateMapper, CouponTemplate, CouponTemplateQueryVO>
        implements CouponTemplateService {

    @Override
    @Transactional(readOnly = false)
    public CouponTemplate createCouponTemplate(CouponTemplate template) {
        if (StrUtil.isNotBlank(template.getId())) {
            throw new BizErrorException("新增优惠券模板不应预置主键");
        }
        getBaseMapper().insert(template);
        return template;
    }

    @Override
    @Transactional(readOnly = false)
    public void updateCouponTemplate(CouponTemplate template) {
        if (StrUtil.isBlank(template.getId())) {
            throw new BizErrorException("更新优惠券模板主键不能为空");
        }
        if (get(template.getId()) == null) {
            throw new BizErrorException("优惠券模板不存在");
        }
        getBaseMapper().update(template);
    }

    @Override
    @Transactional(readOnly = false)
    public boolean increaseIssuedIfQuotaAllows(String id) {
        return baseMapper.increaseIssuedCountIfQuotaAllows(id) > 0;
    }

    @Override
    @Transactional(readOnly = false)
    public void increaseUsedCount(String id) {
        if (StrUtil.isBlank(id)) {
            return;
        }
        baseMapper.increaseUsedCount(id.trim());
    }

    @Override
    @Transactional(readOnly = false)
    public void decreaseUsedCountIfPositive(String id) {
        if (StrUtil.isBlank(id)) {
            return;
        }
        baseMapper.decreaseUsedCountIfPositive(id.trim());
    }

    @Override
    public CouponTemplate findByCouponCode(String couponCode, String tenantId) {
        if (StrUtil.isBlank(couponCode)) {
            return null;
        }
        return getBaseMapper().findByCouponCodeAndTenant(couponCode.trim(), tenantId);
    }

    @Override
    @Transactional(readOnly = false)
    public void updateClaimQrcode(String id, String claimWxScene, String claimQrcodeUrl) {
        if (StrUtil.isBlank(id)) {
            throw new BizErrorException("模板主键不能为空");
        }
        if (getBaseMapper().updateClaimQrcode(id.trim(), claimWxScene, claimQrcodeUrl) <= 0) {
            throw new BizErrorException("优惠券模板不存在或已删除");
        }
    }
}
