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

import com.qqchen.deploy.backend.deploy.converter.EnvironmentConverter;
import com.qqchen.deploy.backend.deploy.dto.EnvironmentDTO;
import com.qqchen.deploy.backend.deploy.entity.Environment;
import com.qqchen.deploy.backend.deploy.entity.QEnvironment;
import com.qqchen.deploy.backend.deploy.query.EnvironmentQuery;
import com.qqchen.deploy.backend.deploy.repository.IEnvironmentRepository;
import com.qqchen.deploy.backend.deploy.service.IEnvironmentService;
import com.qqchen.deploy.backend.framework.service.impl.BaseServiceImpl;
import com.querydsl.jpa.impl.JPAQueryFactory;
import org.springframework.stereotype.Service;
import jakarta.annotation.Resource;
import jakarta.persistence.EntityManager;
import org.springframework.transaction.annotation.Transactional;

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

/**
 * 环境服务实现类
 */
@Service
public class EnvironmentServiceImpl extends BaseServiceImpl<Environment, EnvironmentDTO, EnvironmentQuery, Long> implements IEnvironmentService {

    @Resource
    private IEnvironmentRepository environmentRepository;

    @Resource
    private EnvironmentConverter environmentConverter;

    @Resource
    private EntityManager entityManager;


//    @Override
//    @Transactional
//    public EnvironmentDTO create(EnvironmentDTO dto) {
//        return this.create(dto);
//    }

    @Override
    public List<EnvironmentDTO> getProjectEnvironments(Long projectGroupId) {
        QEnvironment environment = QEnvironment.environment;

        JPAQueryFactory queryFactory = new JPAQueryFactory(entityManager);

        List<Environment> environments = queryFactory
            .select(environment)
            .from(environment)
            .on(environment.id.eq(environment.id))
            .orderBy(environment.sort.asc())
            .fetch();

        return environments.stream()
            .map(environmentConverter::toDto)
            .collect(Collectors.toList());
    }

    @Override
    public void updateProjectEnvironments(Long projectId, List<Long> environmentIds) {
        // TODO: 实现更新逻辑
    }
}