package com.zcloud.personnel.positioning.command;

import com.zcloud.personnel.positioning.dto.TerminalAddCmd;
import com.zcloud.personnel.positioning.domain.gateway.TerminalGateway;
import com.zcloud.personnel.positioning.domain.model.TerminalE;
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 TerminalGateway terminalGateway;
    private final FindsPendingSyncService findsPendingSyncService;

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