package quant.rich.emoney.service.sqlite;

import java.util.function.Supplier;

import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import jakarta.annotation.PostConstruct;
import lombok.extern.slf4j.Slf4j;
import quant.rich.emoney.entity.sqlite.RequestInfo;
import quant.rich.emoney.mapper.sqlite.RequestInfoMapper;
import quant.rich.emoney.patch.okhttp.PatchOkHttp;
import quant.rich.emoney.patch.okhttp.PatchOkHttpRule;

@DS("sqlite")
@Service
@Slf4j
@Lazy(false)
public class RequestInfoService extends SqliteServiceImpl<RequestInfoMapper, RequestInfo> {
    
    private volatile Integer userAgentPatchRuleId;
    
    @PostConstruct
    void postConstruct() {
        userAgentPatchRuleId = PatchOkHttp.apply(
                PatchOkHttpRule.when()
                .hostEndsWith("emoney.cn")
                .not(r -> r.hostMatches("appstatic"))
                .or(a -> a.hostContains("emapp"))
                .or(b -> b.hasHeaderName("X-Protocol-Id"))
                .overrideHeader("User-Agent", new Supplier<String>() {
                    @Override
                    public String get() {
                        log.debug("触发获取请求配置的 OkHttpUserAgent");
                        return getDefaultRequestInfo().getOkHttpUserAgent();
                    }
                }).build().setId(userAgentPatchRuleId));
    }
    
    public RequestInfo getDefaultRequestInfo() {
        RequestInfo requestInfo = getOne(
            new LambdaQueryWrapper<RequestInfo>().eq(RequestInfo::getIsDefault, true)
        );
        if (requestInfo == null) {
            requestInfo = new RequestInfo();
            save(requestInfo);
        }
        return requestInfo;
    }
    
}
