package com.zcloud.personnel.positioning.command;

import com.alibaba.cola.exception.BizException;
import com.zcloud.personnel.positioning.dto.AlarmRuleAddCmd;
import com.zcloud.personnel.positioning.persistence.dataobject.AlarmRuleDO;
import com.zcloud.personnel.positioning.persistence.repository.AlarmRuleRepository;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * web-app
 *
 * @Author fangjiakai
 * @Date 2026-07-07
 */
@Component
@AllArgsConstructor
public class AlarmRuleAddExe {
    private final AlarmRuleRepository alarmRuleRepository;
    private final AlarmRuleConfigPersistence alarmRuleConfigPersistence;
    private final FindsPendingSyncService findsPendingSyncService;

    @Transactional(rollbackFor = Exception.class)
    public boolean execute(AlarmRuleAddCmd cmd) {
        AlarmRuleDO alarmRuleDO = new AlarmRuleDO();
        BeanUtils.copyProperties(cmd, alarmRuleDO);
        alarmRuleConfigPersistence.normalizeRule(alarmRuleDO);
        alarmRuleDO.setSyncStatus(FindsPendingSyncService.STATUS_WAIT);
        alarmRuleDO.setSyncToken(FindsSyncToken.next());
        alarmRuleRepository.save(alarmRuleDO);
        if (alarmRuleDO.getId() == null) {
            throw new BizException("保存失败");
        }
        alarmRuleConfigPersistence.saveNewChildren(alarmRuleDO, cmd.getFenceRelList(), cmd.getRuleItemList());
        findsPendingSyncService.scheduleRule(alarmRuleDO.getId());
        return true;
    }
}
