package com.zcloud.personnel.positioning.command;

import com.alibaba.cola.exception.BizException;
import com.zcloud.personnel.positioning.dto.FenceAddCmd;
import com.zcloud.personnel.positioning.persistence.dataobject.FenceDO;
import com.zcloud.personnel.positioning.persistence.repository.FenceRepository;
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 FenceRepository fenceRepository;
    private final FencePersistenceSupport fencePersistenceSupport;
    private final FindsPendingSyncService findsPendingSyncService;
    private final FencePointPersistenceService fencePointPersistenceService;

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