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

import com.qqchen.deploy.backend.deploy.converter.TeamConverter;
import com.qqchen.deploy.backend.deploy.dto.TeamDTO;
import com.qqchen.deploy.backend.deploy.entity.Team;
import com.qqchen.deploy.backend.deploy.query.TeamQuery;
import com.qqchen.deploy.backend.deploy.repository.ITeamApplicationRepository;
import com.qqchen.deploy.backend.deploy.repository.ITeamMemberRepository;
import com.qqchen.deploy.backend.deploy.repository.ITeamRepository;
import com.qqchen.deploy.backend.deploy.service.ITeamService;
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;

@Slf4j
@Service
public class TeamServiceImpl extends BaseServiceImpl<Team, TeamDTO, TeamQuery, Long>
        implements ITeamService {

    @Resource
    private ITeamRepository teamRepository;

    @Resource
    private ITeamMemberRepository teamMemberRepository;

    @Resource
    private ITeamApplicationRepository teamApplicationRepository;

    @Resource
    private TeamConverter teamConverter;

    @Override
    @Transactional
    public TeamDTO create(TeamDTO dto) {
        // 检查编码唯一性
        if (teamRepository.existsByTeamCodeAndDeletedFalse(dto.getTeamCode())) {
            throw new BusinessException(ResponseCode.TEAM_CODE_EXISTS, new Object[]{dto.getTeamCode()});
        }
        return super.create(dto);
    }

    @Override
    @Transactional
    public void delete(Long id) {
        // 检查是否有成员
        Long memberCount = teamMemberRepository.countByTeamIdAndDeletedFalse(id);
        if (memberCount > 0) {
            throw new BusinessException(ResponseCode.TEAM_HAS_MEMBERS);
        }

        // 检查是否有关联应用
        Long applicationCount = teamApplicationRepository.countByTeamId(id);
        if (applicationCount > 0) {
            throw new BusinessException(ResponseCode.TEAM_HAS_APPLICATIONS);
        }

        super.delete(id);
    }

    @Override
    public Page<TeamDTO> page(TeamQuery query) {
        Page<TeamDTO> page = super.page(query);

        // 统计每个团队的成员数量、环境数量和应用配置数量
        List<TeamDTO> content = page.getContent().stream()
                .peek(team -> {
                    // 统计团队成员数量
                    Long memberCount = teamMemberRepository.countByTeamIdAndDeletedFalse(team.getId());
                    team.setMemberCount(memberCount != null ? memberCount : 0L);
                    
                    // 统计团队可访问的环境数量（去重）
                    Long environmentCount = teamApplicationRepository.countDistinctEnvironmentIdByTeamId(team.getId());
                    team.setEnvironmentCount(environmentCount != null ? environmentCount : 0L);
                    
                    // 统计团队的应用配置数量（不去重，同一应用在不同环境算多个）
                    Long applicationCount = teamApplicationRepository.countByTeamId(team.getId());
                    team.setApplicationCount(applicationCount != null ? applicationCount : 0L);
                })
                .collect(Collectors.toList());

        return new PageImpl<>(content, page.getPageable(), page.getTotalElements());
    }

    @Override
    public List<TeamDTO> findAll(TeamQuery query) {
        List<TeamDTO> list = super.findAll(query);
        
        // 统计每个团队的成员数量、环境数量和应用配置数量
        return list.stream()
                .peek(team -> {
                    // 统计团队成员数量
                    Long memberCount = teamMemberRepository.countByTeamIdAndDeletedFalse(team.getId());
                    team.setMemberCount(memberCount != null ? memberCount : 0L);
                    
                    // 统计团队可访问的环境数量（去重）
                    Long environmentCount = teamApplicationRepository.countDistinctEnvironmentIdByTeamId(team.getId());
                    team.setEnvironmentCount(environmentCount != null ? environmentCount : 0L);
                    
                    // 统计团队的应用配置数量（不去重，同一应用在不同环境算多个）
                    Long applicationCount = teamApplicationRepository.countByTeamId(team.getId());
                    team.setApplicationCount(applicationCount != null ? applicationCount : 0L);
                })
                .collect(Collectors.toList());
    }
}

