package com.zcloud.fire.check.command;

import com.alibaba.cola.exception.BizException;
import com.zcloud.fire.check.domain.gateway.FirePointGateway;
import com.zcloud.fire.check.domain.model.FirePointE;
import com.zcloud.fire.check.dto.FirePointAddCmd;
import com.zcloud.fire.check.persistence.repository.FirePointRepository;
import com.zcloud.fire.check.persistence.repository.FireRegionRepository;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;


/**
 * web-app
 *
 * @Author zhaokai
 * @Date 2025-11-26 10:12:54
 */
@Component
@AllArgsConstructor
public class FirePointAddExe {
    private final FirePointGateway firePointGateway;
    private final FirePointRepository firePointRepository;
    private final FireRegionRepository fireRegionRepository;


    @Transactional(rollbackFor = Exception.class)
    public boolean execute(FirePointAddCmd cmd) {
        //点位编码唯一
        if (firePointRepository.existsByFirePointCode(cmd.getFirePointCode())) {
            throw new BizException("点位编码已存在");
        }
        //校验区域
        fireRegionRepository.checkRegion(cmd.getFireRegionId());
        FirePointE firePointE = new FirePointE();
        BeanUtils.copyProperties(cmd, firePointE);
        boolean res = false;
        try {
            res = firePointGateway.add(firePointE);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        if (!res) {
            throw new BizException("保存失败");
        }
        return true;
    }
}

