package org.qinan.safetyeval.infrastructure.support;

import org.qinan.safetyeval.domain.exception.BizException;
import org.qinan.safetyeval.domain.exception.ErrorCode;
import org.qinan.safetyeval.infrastructure.adapter.ThreadLocalUserInfoAdapter;
import org.qinan.safetyeval.infrastructure.adapter.auth.AuthUserContextAdapter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindException;

import javax.annotation.Resource;

/**
 * 解析写入时的 orgId：优先实体值 → SSO 登录上下文（AuthUserContextAdapter） → ThreadLocal（UserInfoAdapter） → 配置回退（local 联调 org-id=1）。
 */
@Component
public class OrgContextResolver {

    public Long resolveOrgId(Long entityOrgId) {
        if (entityOrgId != null) {
            return entityOrgId;
        }
        Long orgId = ThreadLocalUserInfoAdapter.get();
        if (orgId == null) {
            throw new BizException(ErrorCode.ORG_INFO_NOT_FOUND);
        }
        return orgId;
    }
}
