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

import com.qqchen.deploy.backend.deploy.dto.ProjectGroupDTO;
import com.qqchen.deploy.backend.deploy.entity.Application;
import com.qqchen.deploy.backend.deploy.entity.ProjectGroup;
import com.qqchen.deploy.backend.deploy.query.ProjectGroupQuery;
import com.qqchen.deploy.backend.deploy.repository.IApplicationRepository;
import com.qqchen.deploy.backend.deploy.repository.IEnvironmentRepository;
import com.qqchen.deploy.backend.deploy.repository.IProjectGroupRepository;
import com.qqchen.deploy.backend.deploy.service.IEnvironmentService;
import com.qqchen.deploy.backend.deploy.service.IProjectGroupService;
import com.qqchen.deploy.backend.framework.service.impl.BaseServiceImpl;
import jakarta.annotation.Resource;
import jakarta.persistence.Query;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

import static java.util.stream.Collectors.toList;

@Service
public class ProjectGroupServiceImpl extends BaseServiceImpl<ProjectGroup, ProjectGroupDTO, ProjectGroupQuery, Long> implements IProjectGroupService {

    @Resource
    private IProjectGroupRepository projectGroupRepository;

    @Resource
    private IApplicationRepository applicationRepository;

    @Resource
    private IEnvironmentRepository environmentRepository;


    @Override
    public Page<ProjectGroupDTO> page(ProjectGroupQuery query) {
        Page<ProjectGroupDTO> page = super.page(query);
        List<ProjectGroupDTO> result = page.getContent().stream().map(projectGroupDTO -> {
            projectGroupDTO.setTotalApplications(applicationRepository.countByProjectGroupId(projectGroupDTO.getId()));
            projectGroupDTO.setTotalEnvironments(environmentRepository.countByProjectGroupId(projectGroupDTO.getId()));
            return projectGroupDTO;
        }).collect(toList());
        return new PageImpl<>(result, page.getPageable(), page.getTotalElements());
    }

    @Override
    @Transactional
    public void delete(Long id) {
        // 1. 先删除中间表数据
        Query query = entityManager.createNativeQuery(
            "DELETE FROM deploy_project_group_environment WHERE project_group_id = :projectGroupId"
        );
        query.setParameter("projectGroupId", id);
        query.executeUpdate();

        // 2. 再调用父类的删除方法（逻辑删除ProjectGroup）
        super.delete(id);
    }
} 