package com.zcloud.personnel.positioning.command;

import com.zcloud.personnel.positioning.dto.TerminalAddCmd;
import com.zcloud.personnel.positioning.persistence.dataobject.TerminalDO;
import com.zcloud.personnel.positioning.persistence.repository.TerminalRepository;
import com.alibaba.cola.exception.BizException;
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 TerminalAddExe {
    private final TerminalRepository terminalRepository;
    private final FindsPendingSyncService findsPendingSyncService;

    @Transactional(rollbackFor = Exception.class)
    public boolean execute(TerminalAddCmd cmd) {
        TerminalDO terminal = new TerminalDO();
        BeanUtils.copyProperties(cmd, terminal);
        terminal.setFindsTerminalId(null);
        terminal.setSyncStatus(FindsPendingSyncService.STATUS_WAIT);
        terminal.setSyncToken(FindsSyncToken.next());
        terminal.setLastSyncTime(null);
        terminal.setRawJson(null);
        boolean res = terminalRepository.save(terminal);
        if (!res) {
            throw new BizException("保存失败");
        }
        findsPendingSyncService.scheduleTerminal(terminal.getId());
        return true;
    }
}
