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

import java.util.Date;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.web.modules.industryservice.domain.BizYakHealthSourceRecord;
import com.ruoyi.web.modules.industryservice.mapper.BizYakHealthSourceRecordMapper;

/**
 * 健康源记录落库（独立事务）。
 * <p>
 * 供 {@link YakDiseaseWarningSyncService} 逐条调用：按 {@code external_id} upsert。<br>
 * 更新时保留原 {@code analyzed_flag}，避免已分析记录因内容刷新被再次纳入分析队列。
 * </p>
 */
@Service
public class YakHealthSourceRecordSyncTxService
{
    @Autowired
    private BizYakHealthSourceRecordMapper healthSourceRecordMapper;

    /**
     * 插入或更新一条健康源。
     *
     * @param incoming 已映射好的本地实体（含 externalId、recordType 等）
     * @param syncTime 本轮同步时间
     * @return true=新插入；false=更新已有
     */
    @Transactional(propagation = Propagation.REQUIRES_NEW, rollbackFor = Exception.class)
    public boolean persistSourceRecord(BizYakHealthSourceRecord incoming, Date syncTime)
    {
        incoming.setLastSyncTime(syncTime);
        BizYakHealthSourceRecord existing = healthSourceRecordMapper.selectByExternalId(incoming.getExternalId());
        if (existing == null)
        {
            healthSourceRecordMapper.insertBizYakHealthSourceRecord(incoming);
            return true;
        }
        incoming.setId(existing.getId());
        // 保留已分析标记，防止内容更新把记录重新推入未分析队列
        incoming.setAnalyzedFlag(existing.getAnalyzedFlag());
        healthSourceRecordMapper.updateBizYakHealthSourceRecord(incoming);
        return false;
    }
}
