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.ThirdPartyFarmingPlanClient;

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

    @Autowired
    private ThirdPartyFarmingPlanClient thirdPartyFarmingPlanClient;

    @Autowired
    private FarmingPlanSyncTxService farmingPlanSyncTxService;

    /**
     * 从第三方拉取全量生产计划并 upsert 到本地。
     */
    public YakAssetSyncResultVo syncFromThirdParty()
    {
        if (!syncing.compareAndSet(false, true))
        {
            throw new ServiceException(FarmingSyncRules.MSG_SYNC_IN_PROGRESS);
        }
        try
        {
            return FarmingDataSyncExecutor.execute(thirdPartyFarmingPlanClient.fetchAll(),
                    farmingPlanSyncTxService::persistPlan,
                    dto -> dto != null && dto.getId() != null ? String.valueOf(dto.getId()) : null);
        }
        finally
        {
            syncing.set(false);
        }
    }
}
