package com.lesingle.creation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.lesingle.creation.common.security.UserPrincipal;
import com.lesingle.creation.entity.Permission;
import com.lesingle.creation.entity.Tenant;
import com.lesingle.creation.entity.User;
import com.lesingle.creation.entity.UserRole;
import com.lesingle.creation.entity.RolePermission;
import com.lesingle.creation.mapper.TenantMapper;
import com.lesingle.creation.mapper.UserMapper;
import com.lesingle.creation.mapper.UserRoleMapper;
import com.lesingle.creation.mapper.RolePermissionMapper;
import com.lesingle.creation.mapper.PermissionMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
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 java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * Spring Security UserDetailsService 实现类
 * 用于加载用户信息进行认证
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {

    private final UserMapper userMapper;
    private final TenantMapper tenantMapper;
    private final UserRoleMapper userRoleMapper;
    private final RolePermissionMapper rolePermissionMapper;
    private final PermissionMapper permissionMapper;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.debug("加载用户信息：{}", username);

        // 支持通过用户 ID 或用户名查询
        User user;
        try {
            // 尝试通过用户 ID 查询（JWT token 中 subject 是用户 ID）
            Long userId = Long.parseLong(username);
            user = userMapper.selectById(userId);
            if (user != null && user.getDeleted() == 0) {
                log.debug("通过用户 ID 找到用户：{}, username: {}", userId, user.getUsername());
            } else {
                // 如果通过 ID 没找到，尝试通过用户名查询
                user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                        .eq(User::getUsername, username)
                        .eq(User::getDeleted, 0));
                log.debug("通过用户名查询用户：{}, 结果：{}", username, user != null ? "找到" : "未找到");
            }
        } catch (NumberFormatException e) {
            // 不是数字，通过用户名查询
            user = userMapper.selectOne(new LambdaQueryWrapper<User>()
                    .eq(User::getUsername, username)
                    .eq(User::getDeleted, 0));
            log.debug("通过用户名查询用户：{}, 结果：{}", username, user != null ? "找到" : "未找到");
        }

        if (user == null) {
            log.warn("用户不存在：{}", username);
            throw new UsernameNotFoundException("用户不存在：" + username);
        }

        // 查询租户信息
        Tenant tenant = tenantMapper.selectById(user.getTenantId());
        String tenantCode = tenant != null ? tenant.getCode() : "default";

        // 查询用户角色
        List<UserRole> userRoles = userRoleMapper.selectList(new LambdaQueryWrapper<UserRole>()
                .eq(UserRole::getUserId, user.getId()));

        // 查询角色权限
        List<String> permissionCodes = new ArrayList<>();
        if (!userRoles.isEmpty()) {
            List<Long> roleIds = userRoles.stream().map(UserRole::getRoleId).collect(Collectors.toList());
            List<RolePermission> rolePermissions = rolePermissionMapper.selectList(
                new LambdaQueryWrapper<RolePermission>()
                    .in(RolePermission::getRoleId, roleIds)
            );

            if (!rolePermissions.isEmpty()) {
                List<Long> permissionIds = rolePermissions.stream()
                    .map(RolePermission::getPermissionId)
                    .collect(Collectors.toList());
                List<Permission> permissions = permissionMapper.selectList(
                    new LambdaQueryWrapper<Permission>()
                        .in(Permission::getId, permissionIds)
                        .eq(Permission::getDeleted, 0)
                );
                permissionCodes = permissions.stream()
                    .map(Permission::getCode)
                    .collect(Collectors.toList());
            }
        }

        // 构建 authorities
        List<SimpleGrantedAuthority> authorities = permissionCodes.stream()
            .map(code -> new SimpleGrantedAuthority(code))
            .collect(Collectors.toList());

        log.debug("用户 {} 的权限列表：{}", user.getUsername(), permissionCodes);

        // 构建 UserPrincipal 对象（包含用户 ID、租户 ID、租户编码等信息）
        UserPrincipal userPrincipal = new UserPrincipal(
                user.getId(),
                user.getUsername(),
                user.getPassword(),
                authorities,
                user.getTenantId(),
                tenantCode,
                "platform".equals(tenantCode)  // platform 租户为超级租户
        );

        log.debug("用户加载成功：{}, 租户 ID: {}", user.getUsername(), user.getTenantId());

        return userPrincipal;
    }
}
