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

/**
 * 第三方<strong>养殖圈舍</strong>同步编排。
 * <p>
 * 接口：{@code GET /open-api/v1/farming/enclosures} → 落库 {@code biz_farm_enclosure}。
 * 通常由 {@link LivestockFinanceMasterSyncService} 在养殖场同步之后调用；
 * 也可在全量同步流程中单独作为第二步执行。
 * </p>
 * <p>
 * 每条圈舍记录通过 {@link FarmEnclosureSyncTxService} 以 {@code REQUIRES_NEW} 独立事务写入，
 * 单条失败计入 {@link YakAssetSyncResultVo#getFailCount()}，不影响同批其他圈舍。
 * </p>
 */
@Service
public class FarmEnclosureSyncService
{
    /** 防并发重入：同一时刻只允许一个圈舍同步任务 */
    private final AtomicBoolean syncing = new AtomicBoolean(false);

    @Autowired
    private ThirdPartyFarmEnclosureClient thirdPartyFarmEnclosureClient;

    @Autowired
    private FarmEnclosureSyncTxService farmEnclosureSyncTxService;

    /**
     * 从第三方拉取全量圈舍列表并 upsert 到本地。
     *
     * @return 新增/更新/失败条数及失败明细（key 为第三方 id）
     */
    public YakAssetSyncResultVo syncFromThirdParty()
    {
        if (!syncing.compareAndSet(false, true))
        {
            throw new ServiceException(FarmingSyncRules.MSG_SYNC_IN_PROGRESS);
        }
        try
        {
            return FarmingDataSyncExecutor.execute(thirdPartyFarmEnclosureClient.fetchAll(),
                    farmEnclosureSyncTxService::persistEnclosure,
                    dto -> dto != null && dto.getId() != null ? String.valueOf(dto.getId()) : null);
        }
        finally
        {
            syncing.set(false);
        }
    }
}
