package com.qqchen.deploy.backend.deploy.service.impl;

import com.qqchen.deploy.backend.deploy.dto.ApplicationCategoryDTO;
import com.qqchen.deploy.backend.deploy.entity.ApplicationCategory;
import com.qqchen.deploy.backend.deploy.query.ApplicationCategoryQuery;
import com.qqchen.deploy.backend.deploy.repository.IApplicationCategoryRepository;
import com.qqchen.deploy.backend.deploy.repository.IApplicationRepository;
import com.qqchen.deploy.backend.deploy.service.IApplicationCategoryService;
import com.qqchen.deploy.backend.framework.enums.ResponseCode;
import com.qqchen.deploy.backend.framework.exception.BusinessException;
import com.qqchen.deploy.backend.framework.service.impl.BaseServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

/**
 * 应用分类Service实现
 */
@Slf4j
@Service
public class ApplicationCategoryServiceImpl extends BaseServiceImpl<ApplicationCategory, ApplicationCategoryDTO, ApplicationCategoryQuery, Long>
        implements IApplicationCategoryService {

    @Resource
    private IApplicationCategoryRepository applicationCategoryRepository;

    @Resource
    private IApplicationRepository applicationRepository;

    @Override
    @Transactional
    public ApplicationCategoryDTO create(ApplicationCategoryDTO dto) {
        // 检查编码唯一性
        if (applicationCategoryRepository.existsByCodeAndDeletedFalse(dto.getCode())) {
            throw new BusinessException(ResponseCode.APPLICATION_CATEGORY_CODE_EXISTS, new Object[]{dto.getCode()});
        }
        return super.create(dto);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        // 检查是否有关联的应用
        Long applicationCount = applicationRepository.countByApplicationCategoryIdAndDeletedFalse(id);
        if (applicationCount > 0) {
            throw new BusinessException(ResponseCode.APPLICATION_CATEGORY_HAS_APPLICATIONS);
        }
        super.delete(id);
    }

    @Override
    public Page<ApplicationCategoryDTO> page(ApplicationCategoryQuery query) {
        Page<ApplicationCategoryDTO> page = super.page(query);
        
        // 统计每个分类的应用数量
        List<ApplicationCategoryDTO> content = page.getContent().stream()
                .peek(category -> {
                    Long count = applicationRepository.countByApplicationCategoryIdAndDeletedFalse(category.getId());
                    category.setApplicationCount(count);
                })
                .collect(Collectors.toList());
        
        return new PageImpl<>(content, page.getPageable(), page.getTotalElements());
    }
}

