package com.jeesharp.business.modules.mall.application;

import cn.hutool.core.util.StrUtil;
import com.jeesharp.business.modules.mall.convert.MallCategoryConvert;
import com.jeesharp.business.modules.mall.dto.MallCategorySaveDTO;
import com.jeesharp.business.modules.mall.entity.MallCategory;
import com.jeesharp.business.modules.mall.enums.MallCategoryStatusEnum;
import com.jeesharp.business.modules.mall.service.MallCategoryService;
import com.jeesharp.business.modules.mall.vo.MallCategoryInfoVO;
import com.jeesharp.business.modules.mall.vo.MallCategoryListVO;
import com.jeesharp.business.modules.mall.vo.MallCategoryQueryVO;
import com.jeesharp.framework.pojo.Page;
import com.jeesharp.framework.pojo.query.PageRespVO;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * 商品类目 Application Service
 */
@Service
@AllArgsConstructor
@Transactional(readOnly = true)
public class MallCategoryApplicationService {

    private final MallCategoryService mallCategoryService;

    public MallCategoryInfoVO get(String id) {
        return MallCategoryConvert.INSTANCE.toInfoVO(mallCategoryService.get(id));
    }

    /**
     * C 端门户：查询已启用的分类列表（按 {@code sortOrder} 升序）。
     */
    public List<MallCategoryInfoVO> listEnabledForPortal() {
        return mallCategoryService.listEnabledForPortal().stream()
                .map(MallCategoryConvert.INSTANCE::toInfoVO)
                .toList();
    }

    public PageRespVO<MallCategoryListVO> findPage(Page<MallCategory> page, MallCategoryQueryVO query) {
        Page<MallCategory> result = mallCategoryService.findPage(page, query);
        return MallCategoryConvert.INSTANCE.toPageRespVO(result);
    }

    /**
     * 建品用类目列表：固定返回平台租户下已启用类目（商户与平台共用）。
     */
    public List<MallCategoryListVO> listForPublish() {
        return MallCategoryConvert.INSTANCE.toListVO(mallCategoryService.listPlatformEnabledForPublish());
    }

    @Transactional(readOnly = false)
    public void save(MallCategorySaveDTO dto) {
        MallCategory entity = MallCategoryConvert.INSTANCE.toEntity(dto);
        if (StrUtil.isBlank(dto.getId())) {
            mallCategoryService.createCategory(entity);
            return;
        }
        mallCategoryService.updateCategory(entity);
    }

    @Transactional(readOnly = false)
    public void delete(String ids) {
        mallCategoryService.batchDelete(StrUtil.splitTrim(ids, ','));
    }
}
