package com.zcloud.zcGbsServicer.command;

import com.alibaba.cola.exception.BizException;
import com.zcloud.zcGbsServicer.domain.enums.DeviceTypeEnum;
import com.zcloud.zcGbsServicer.domain.gateway.PumpRoomGateway;
import com.zcloud.zcGbsServicer.domain.gateway.ResourceDeviceGateway;
import com.zcloud.zcGbsServicer.persistence.dataobject.PumpRoomDO;
import com.zcloud.zcGbsServicer.persistence.repository.PumpRoomRepository;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

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

/**
* web-app
* @Author makejava
* @Date 2026-01-21 17:22:16
*/
@Component
@AllArgsConstructor
public class PumpRoomRemoveExe {
    private final PumpRoomGateway pumpRoomGateway;
    private final PumpRoomRepository pumpRoomRepository;
    private final ResourceDeviceGateway resourceDeviceGateway;

    @Transactional(rollbackFor = Exception.class)
    public boolean execute(Long id) {
        PumpRoomDO pumpRoomDO = pumpRoomRepository.getById(id);
        if (pumpRoomDO == null) {
            throw new BizException("数据不存在");
        }
        boolean res = pumpRoomGateway.deletedPumpRoomById(id);
        boolean resDelDev = resourceDeviceGateway.deletedResourceDeviceByBizId(
                pumpRoomDO.getPumpRoomId(), DeviceTypeEnum.PUMP_ROOM.getCode());
        if (!res || !resDelDev) {
            throw new BizException("删除失败");
        }
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean execute(Long[] ids) {
        if (ids == null || ids.length == 0) {
            return true;
        }
        List<String> pumpRoomIds = Arrays.stream(ids)
                .map(pumpRoomRepository::getById)
                .filter(Objects::nonNull)
                .map(PumpRoomDO::getPumpRoomId)
                .collect(Collectors.toList());

        boolean res = pumpRoomGateway.deletedPumpRoomByIds(ids);
        boolean resDelDev = true;
        for (String pumpRoomId : pumpRoomIds) {
            resDelDev = resDelDev && resourceDeviceGateway.deletedResourceDeviceByBizId(
                    pumpRoomId, DeviceTypeEnum.PUMP_ROOM.getCode());
        }
        if (!res || !resDelDev) {
            throw new BizException("Delete failed");
        }
        return true;
    }
}
