package cn.nianxx.thhotel.integrations.ai.superagent.repository;

import cn.nianxx.thhotel.integrations.ai.superagent.domain.SuperAgentTaskResultNonceEntity;
import cn.nianxx.thhotel.integrations.ai.superagent.mapper.SuperAgentTaskResultNonceMapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import java.time.LocalDateTime;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Repository;

/**
 * SuperAgent nonce 的 MyBatis-Plus 持久化实现。数据库唯一键是防重放最终防线。
 */
@Repository
public class MybatisSuperAgentTaskResultNonceRepository implements SuperAgentTaskResultNonceRepository {

    private final SuperAgentTaskResultNonceMapper nonceMapper;

    /**
     * 注入 nonce Mapper，Repository 负责屏蔽唯一键冲突细节。
     */
    public MybatisSuperAgentTaskResultNonceRepository(SuperAgentTaskResultNonceMapper nonceMapper) {
        this.nonceMapper = nonceMapper;
    }

    /**
     * 插入 nonce 防重放记录；并发重复请求会命中唯一键并返回 false。
     */
    @Override
    public boolean saveIfAbsent(String clientId, String nonce, LocalDateTime expiresAt, LocalDateTime createdAt) {
        nonceMapper.delete(Wrappers.<SuperAgentTaskResultNonceEntity>lambdaQuery()
                .eq(SuperAgentTaskResultNonceEntity::getClientId, clientId)
                .eq(SuperAgentTaskResultNonceEntity::getNonce, nonce)
                .lt(SuperAgentTaskResultNonceEntity::getExpiresAt, createdAt));
        SuperAgentTaskResultNonceEntity entity = new SuperAgentTaskResultNonceEntity();
        entity.setClientId(clientId);
        entity.setNonce(nonce);
        entity.setExpiresAt(expiresAt);
        entity.setCreatedAt(createdAt);
        try {
            nonceMapper.insert(entity);
            return true;
        } catch (DuplicateKeyException exception) {
            return false;
        }
    }
}
