package com.zcloud.personnel.positioning.command;

import com.alibaba.cola.exception.BizException;
import com.zcloud.personnel.positioning.persistence.dataobject.TerminalDO;
import com.zcloud.personnel.positioning.persistence.repository.TerminalRepository;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * web-app
 *
 * @Author fangjiakai
 * @Date 2026-07-07
 */
@Component
@AllArgsConstructor
public class TerminalRemoveExe {
    private final TerminalRepository terminalRepository;
    private final FindsPendingSyncService findsPendingSyncService;

    @Transactional(rollbackFor = Exception.class)
    public boolean execute(Long id) {
        TerminalDO terminal = terminalRepository.getById(id);
        if (terminal == null) {
            throw new BizException("终端不存在");
        }
        terminal.setSyncStatus(FindsPendingSyncService.STATUS_DELETE_WAIT);
        terminal.setSyncToken(FindsSyncToken.next());
        boolean res = terminalRepository.updateById(terminal);
        if (!res) {
            throw new BizException("删除失败");
        }
        findsPendingSyncService.scheduleTerminal(id);
        return true;
    }

    @Transactional(rollbackFor = Exception.class)
    public boolean execute(Long[] ids) {
        if (ids == null || ids.length == 0) {
            return true;
        }
        for (Long id : ids) {
            execute(id);
        }
        return true;
    }
}
