package org.xyzh.auth.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.xyzh.auth.domain.UserPrincipal;
import org.xyzh.common.dto.user.TbSysUser;
import org.xyzh.common.dto.dept.TbSysDeptRole;
import org.xyzh.common.dto.permission.TbSysPermission;
import org.xyzh.api.system.user.UserService;
import org.xyzh.api.system.role.RoleService;
import org.xyzh.api.system.permission.PermissionService;

import java.util.List;
import java.util.ArrayList;

/**
 * @description    UserDetailsServiceImpl.java文件描述 用户详情服务实现
 * @filename    UserDetailsServiceImpl.java
 * @author    yslg
 * @copyright xyzh
 * @since 2025-09-28
 */
@Service
public class UserDetailsServiceImpl implements UserDetailsService {

    private static final Logger logger = LoggerFactory.getLogger(UserDetailsServiceImpl.class);

    @Autowired
    private UserService userService;

    @Autowired(required = false)
    private RoleService roleService;

    @Autowired(required = false)
    private PermissionService permissionService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        TbSysUser filter = new TbSysUser();
        filter.setUsername(username);
        List<TbSysUser> users = userService.getUserByFilter(filter).getDataList();
        if(users.isEmpty()) {
            throw new UsernameNotFoundException("用户不存在: " + username);
        }
        TbSysUser user = users.get(0);
        
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在: " + username);
        }

        return loadUserByUserId(user.getID());
    }

    /**
     * @description    根据用户ID加载用户详情
     * @param    userId 用户ID
     * @return    UserDetails 用户详情
     * @author    yslg
     * @since 2025-09-28
     */
    public UserDetails loadUserByUserId(String userId) {
        TbSysUser filter = new TbSysUser();
        filter.setID(userId);
        List<TbSysUser> users = userService.getUserByFilter(filter).getDataList();
        if(users.isEmpty()) {
            throw new UsernameNotFoundException("用户不存在: " + userId);
        }
        TbSysUser user = users.get(0);
        
        if (user == null) {
            throw new UsernameNotFoundException("用户不存在: " + userId);
        }

        // 获取用户角色（如果角色服务可用）
        List<TbSysDeptRole> roles = new ArrayList<>();
        if (roleService != null) {
            try {
                // TODO: 需要在RoleService中实现findRolesByUserId方法
                // roles = roleService.findRolesByUserId(userId);
            } catch (Exception e) {
                logger.warn("无法获取用户角色: " + e.getMessage());
            }
        }
        
        // 获取用户权限（如果权限服务可用）
        List<TbSysPermission> permissions = new ArrayList<>();
        if (permissionService != null) {
            try {
                // TODO: 需要在PermissionService中实现findPermissionsByUserId方法
                // permissions = permissionService.findPermissionsByUserId(userId);
            } catch (Exception e) {
                logger.warn("无法获取用户权限: " + e.getMessage());
            }
        }

        return UserPrincipal.create(user, roles, permissions);
    }
}
