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

import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.mall.entity.MallFirstOrderConfig;
import com.jeesharp.business.modules.mall.enums.MallFirstOrderConfigStatusEnum;
import com.jeesharp.business.modules.mall.mapper.MallFirstOrderConfigMapper;
import com.jeesharp.business.modules.mall.mapper.MallOrderMapper;
import com.jeesharp.business.modules.mall.service.MallFirstOrderConfigService;
import com.jeesharp.business.modules.mall.vo.MallFirstOrderConfigQueryVO;
import com.jeesharp.framework.mybatis.core.service.CrudService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * 首单优惠配置领域服务：持久化与首单资格查询（基于商城订单计数）。
 *
 * @author jeesharp
 * @since 2026-02-05
 */
@Service
@Transactional(readOnly = true)
public class MallFirstOrderConfigServiceImpl
        extends CrudService<MallFirstOrderConfigMapper, MallFirstOrderConfig, MallFirstOrderConfigQueryVO>
        implements MallFirstOrderConfigService {

    private static final String IDS_SEPARATOR = ",";

    @Autowired
    private MallOrderMapper mallOrderMapper;

    @Override
    @Transactional(readOnly = false)
    public void createConfig(MallFirstOrderConfig entity) {
        save(entity);
    }

    @Override
    @Transactional(readOnly = false)
    public void updateConfig(MallFirstOrderConfig entity) {
        update(entity);
    }

    @Override
    public MallFirstOrderConfig getEnabledConfig() {
        MallFirstOrderConfigQueryVO query = new MallFirstOrderConfigQueryVO();
        query.setStatus(MallFirstOrderConfigStatusEnum.ENABLED.getValue());
        List<MallFirstOrderConfig> list = findList(query);
        return list.isEmpty() ? null : list.get(0);
    }

    @Override
    public boolean checkIsFirstOrder(String memberId) {
        if (StrUtil.isBlank(memberId)) {
            return false;
        }
        return mallOrderMapper.countActiveOrdersByMemberId(memberId) == 0;
    }

    @Override
    public boolean isFirstPaidOrder(String memberId) {
        if (StrUtil.isBlank(memberId)) {
            return false;
        }
        return mallOrderMapper.countPaidOrdersByMemberId(memberId) == 1;
    }
}
