package com.ruoyi.web.modules.industryservice.service;

import java.util.concurrent.atomic.AtomicBoolean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.web.modules.industryservice.domain.vo.YakAssetSyncResultVo;
import com.ruoyi.web.modules.industryservice.support.FarmingDataSyncExecutor;
import com.ruoyi.web.modules.industryservice.support.FarmingSyncRules;
import com.ruoyi.web.modules.industryservice.support.ThirdPartyFarmingBatchClient;

/**
 * 第三方<strong>养殖批次</strong>同步编排。
 * <p>
 * 接口：{@code GET /open-api/v1/farming/batches} → 落库 {@code biz_farming_batch}。
 * 在全量同步中位于生产计划之后、入栏建档之前执行。
 * </p>
 */
@Service
public class FarmingBatchSyncService
{
    private final AtomicBoolean syncing = new AtomicBoolean(false);

    @Autowired
    private ThirdPartyFarmingBatchClient thirdPartyFarmingBatchClient;

    @Autowired
    private FarmingBatchSyncTxService farmingBatchSyncTxService;

    /**
     * 从第三方拉取全量养殖批次并 upsert 到本地。
     */
    public YakAssetSyncResultVo syncFromThirdParty()
    {
        if (!syncing.compareAndSet(false, true))
        {
            throw new ServiceException(FarmingSyncRules.MSG_SYNC_IN_PROGRESS);
        }
        try
        {
            return FarmingDataSyncExecutor.execute(thirdPartyFarmingBatchClient.fetchAll(),
                    farmingBatchSyncTxService::persistBatch,
                    dto -> dto != null && dto.getId() != null ? String.valueOf(dto.getId()) : null);
        }
        finally
        {
            syncing.set(false);
        }
    }
}
