package com.zcloud.personnel.positioning.command;

import com.alibaba.cola.exception.BizException;
import com.zcloud.personnel.positioning.domain.gateway.AlarmRuleGateway;
import com.zcloud.personnel.positioning.domain.model.AlarmRuleE;
import com.zcloud.personnel.positioning.dto.AlarmRuleAddCmd;
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 AlarmRuleGateway alarmRuleGateway;
    private final AlarmRuleConfigPersistence alarmRuleConfigPersistence;
    private final FindsPendingSyncService findsPendingSyncService;

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