package com.nanri.aiimage.modules.shopkey.service;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nanri.aiimage.common.exception.BusinessException;
import com.nanri.aiimage.modules.shopkey.mapper.ShopManageGroupMapper;
import com.nanri.aiimage.modules.shopkey.mapper.ShopManageMapper;
import com.nanri.aiimage.modules.shopkey.model.dto.ShopManageGroupCreateRequest;
import com.nanri.aiimage.modules.shopkey.model.dto.ShopManageGroupUpdateRequest;
import com.nanri.aiimage.modules.shopkey.model.entity.ShopManageGroupEntity;
import com.nanri.aiimage.modules.shopkey.model.entity.ShopManageEntity;
import com.nanri.aiimage.modules.shopkey.model.vo.ShopManageGroupItemVo;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@RequiredArgsConstructor
public class ShopManageGroupService {

    private final ShopManageGroupMapper groupMapper;
    private final ShopManageMapper shopManageMapper;

    public List<ShopManageGroupItemVo> list() {
        return groupMapper.selectList(new LambdaQueryWrapper<ShopManageGroupEntity>().orderByAsc(ShopManageGroupEntity::getId))
                .stream()
                .map(this::toVo)
                .toList();
    }

    @Transactional
    public ShopManageGroupItemVo create(ShopManageGroupCreateRequest request) {
        String groupName = normalizeRequired(request.getGroupName(), "分组名称不能为空");
        ensureGroupNameUnique(groupName, null);
        ShopManageGroupEntity entity = new ShopManageGroupEntity();
        entity.setGroupName(groupName);
        groupMapper.insert(entity);
        return toVo(getById(entity.getId()));
    }

    @Transactional
    public ShopManageGroupItemVo update(Long id, ShopManageGroupUpdateRequest request) {
        ShopManageGroupEntity entity = getById(id);
        String groupName = normalizeRequired(request.getGroupName(), "分组名称不能为空");
        ensureGroupNameUnique(groupName, id);
        entity.setGroupName(groupName);
        groupMapper.updateById(entity);
        return toVo(getById(id));
    }

    @Transactional
    public void delete(Long id) {
        ShopManageGroupEntity entity = getById(id);
        Long useCount = shopManageMapper.selectCount(new LambdaQueryWrapper<ShopManageEntity>().eq(ShopManageEntity::getGroupId, entity.getId()));
        if (useCount != null && useCount > 0) {
            throw new BusinessException("该分组下存在店铺，无法删除");
        }
        groupMapper.deleteById(entity.getId());
    }

    public ShopManageGroupEntity getById(Long id) {
        ShopManageGroupEntity entity = groupMapper.selectById(id);
        if (entity == null) {
            throw new BusinessException("分组不存在");
        }
        return entity;
    }

    private void ensureGroupNameUnique(String groupName, Long excludeId) {
        LambdaQueryWrapper<ShopManageGroupEntity> query = new LambdaQueryWrapper<ShopManageGroupEntity>()
                .eq(ShopManageGroupEntity::getGroupName, groupName);
        if (excludeId != null) {
            query.ne(ShopManageGroupEntity::getId, excludeId);
        }
        Long count = groupMapper.selectCount(query);
        if (count != null && count > 0) {
            throw new BusinessException("分组名称已存在");
        }
    }

    private String normalizeRequired(String value, String message) {
        String normalized = value == null ? "" : value.trim();
        if (normalized.isEmpty()) {
            throw new BusinessException(message);
        }
        return normalized;
    }

    private ShopManageGroupItemVo toVo(ShopManageGroupEntity entity) {
        ShopManageGroupItemVo vo = new ShopManageGroupItemVo();
        vo.setId(entity.getId());
        vo.setGroupName(entity.getGroupName());
        vo.setCreatedAt(entity.getCreatedAt());
        vo.setUpdatedAt(entity.getUpdatedAt());
        return vo;
    }
}
