package com.infoepoch.pms.agent.service.auth;

import com.infoepoch.pms.agent.domain.baisc.user.User;
import com.infoepoch.pms.agent.domain.baisc.user.UserCriteria;
import com.infoepoch.pms.agent.domain.baisc.user.UserQueryService;
import com.infoepoch.pms.agent.platform.shared.exception.BusinessException;
import com.infoepoch.pms.agent.platform.shared.response.ResultCode;
import com.infoepoch.pms.agent.service.auth.dto.LoginSessionUser;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 目标系统用户匹配服务。
 * <p>
 * 根据 SSO 用户名查找本系统对应的可用用户。
 * </p>
 */
@Service
@RequiredArgsConstructor
public class TargetUserService {

    private final UserQueryService userQueryService;

    /**
     * 根据 SSO 用户名查找本系统对应的可用用户。需精确匹配且唯一、未被禁用。
     *
     * @param username SSO 用户名
     * @return 登录会话用户信息
     * @throws BusinessException 用户不存在、不唯一或已禁用时
     */
    public LoginSessionUser findLoginSessionUser(String username) {
        if (StringUtils.isBlank(username)) {
            throw new BusinessException(ResultCode.PARAM_ERROR, "单点登录失败，Token 缺少用户名");
        }
        UserCriteria criteria = new UserCriteria();
        criteria.setUsernameList(List.of(username));
        criteria.setDisabled(false);

        List<User> users = userQueryService.popupListNotRela(criteria).stream()
                .filter(user -> username.equals(user.getUsername()))
                .toList();
        if (users.isEmpty()) {
            throw new BusinessException(ResultCode.PARAM_ERROR, "单点登录失败，目标系统不存在该用户");
        }
        if (users.size() > 1) {
            throw new BusinessException(ResultCode.PARAM_ERROR, "单点登录失败，目标系统用户匹配不唯一");
        }
        User user = users.get(0);
        if (user.isDisabled()) {
            throw new BusinessException(ResultCode.PARAM_ERROR, "单点登录失败，目标系统用户已禁用");
        }
        return new LoginSessionUser(
                user.getId(),
                user.getUsername(),
                user.getFullname(),
                user.getOrganizationId(),
                user.getOrganizationName()
        );
    }
}
