package com.zcloud.personnel.positioning.command;

import com.alibaba.cola.exception.BizException;
import com.zcloud.personnel.positioning.domain.gateway.FenceGateway;
import com.zcloud.personnel.positioning.domain.model.FenceE;
import com.zcloud.personnel.positioning.dto.FenceAddCmd;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

@Component
@AllArgsConstructor
public class FenceAddExe {
    private final FenceGateway fenceGateway;
    private final FencePersistenceSupport fencePersistenceSupport;
    private final FindsPendingSyncService findsPendingSyncService;
    private final FencePointPersistenceService fencePointPersistenceService;

    @Transactional(rollbackFor = Exception.class)
    public Long execute(FenceAddCmd cmd) {
        FenceE fence = new FenceE();
        BeanUtils.copyProperties(cmd, fence);
        fencePersistenceSupport.normalize(fence, true);
        fence.setSyncStatus(FindsPendingSyncService.STATUS_WAIT);
        fence.setSyncToken(FindsSyncToken.next());
        boolean res = fenceGateway.add(fence);
        if (!res) {
            throw new BizException("Fence save failed");
        }
        fencePointPersistenceService.rebuild(fence);
        findsPendingSyncService.scheduleFence(fence.getId());
        return fence.getId();
    }
}
