package com.jeesharp.business.modules.marketing.tenantExt.application;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.marketing.tenantExt.convert.MarketingTenantExtConvert;
import com.jeesharp.business.modules.marketing.tenantExt.dto.MarketingTenantExtSaveDTO;
import com.jeesharp.business.modules.marketing.tenantExt.entity.MarketingTenantExt;
import com.jeesharp.business.modules.marketing.tenantExt.service.MarketingTenantExtService;
import com.jeesharp.business.modules.marketing.tenantExt.vo.MarketingTenantExtInfoVO;
import com.jeesharp.business.modules.marketing.tenantExt.vo.MarketingTenantExtQueryVO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 店铺营销扩展配置应用服务。
 *
 * @author jeesharp
 * @since 2026-06-25
 */
@Service
@AllArgsConstructor
@Transactional(readOnly = true)
public class MarketingTenantExtApplicationService {

    private final MarketingTenantExtService marketingTenantExtService;

    public MarketingTenantExtInfoVO getCurrent() {
        MarketingTenantExtQueryVO query = new MarketingTenantExtQueryVO();
        List<MarketingTenantExt> list = marketingTenantExtService.findList(query);
        if (CollUtil.isEmpty(list)) {
            return defaultInfo();
        }
        return MarketingTenantExtConvert.INSTANCE.toInfoVO(list.get(0));
    }

    public MarketingTenantExtInfoVO getByTenantId(String tenantId) {
        if (StrUtil.isBlank(tenantId)) {
            return defaultInfo();
        }
        MarketingTenantExt entity = marketingTenantExtService.getByTenantId(tenantId);
        if (entity == null) {
            MarketingTenantExtInfoVO vo = defaultInfo();
            vo.setTenantId(tenantId);
            return vo;
        }
        return MarketingTenantExtConvert.INSTANCE.toInfoVO(entity);
    }

    @Transactional(readOnly = false)
    public void update(MarketingTenantExtSaveDTO dto) {
        if (StrUtil.isNotBlank(dto.getId())) {
            marketingTenantExtService.updateMarketingTenantExt(MarketingTenantExtConvert.INSTANCE.toEntity(dto));
            return;
        }
        List<MarketingTenantExt> existing = marketingTenantExtService.findList(new MarketingTenantExtQueryVO());
        if (CollUtil.isNotEmpty(existing)) {
            MarketingTenantExt entity = MarketingTenantExtConvert.INSTANCE.toEntity(dto);
            entity.setId(existing.get(0).getId());
            marketingTenantExtService.updateMarketingTenantExt(entity);
            return;
        }
        marketingTenantExtService.createMarketingTenantExt(MarketingTenantExtConvert.INSTANCE.toEntity(dto));
    }

    private MarketingTenantExtInfoVO defaultInfo() {
        MarketingTenantExtInfoVO vo = new MarketingTenantExtInfoVO();
        vo.setMarketingEnabled(0);
        vo.setAutoJoinOnQr(1);
        return vo;
    }
}
