package com.yaoyuan.jiscuss.service.impl;

import com.yaoyuan.jiscuss.entity.User;
import com.yaoyuan.jiscuss.entity.UserInfo;
import com.yaoyuan.jiscuss.repository.UserRoleRepository;
import com.yaoyuan.jiscuss.service.IUsersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

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

/**
 * Spring Security {@code UserDetailsService} implementation.
 *
 * <p>Role assignment: users with {@code level >= 1} receive {@code ROLE_ADMIN};
 * all others receive {@code ROLE_USER}.
 *
 * <p>Password note: passwords stored in the database MUST be BCrypt-hashed.
 * See Flyway migration {@code V2__security_updates.sql} for the one-time migration
 * that converts legacy plaintext passwords to BCrypt hashes and expands the column.
 */
@Component
public class UserDetailServiceImpl implements UserDetailsService {

    @Autowired
    private IUsersService userInfoService;

    @Autowired
    private UserRoleRepository userRoleRepository;

    @Override
    public UserInfo loadUserByUsername(String username) throws UsernameNotFoundException {
        User userInfo = userInfoService.getByUsername(username);
        if (userInfo == null) {
            throw new UsernameNotFoundException("用户不存在: " + username);
        }

        List<GrantedAuthority> authorities = new ArrayList<>();
        List<String> roleCodes = userRoleRepository.findRoleCodesByUserId(userInfo.getId());
        if (roleCodes == null || roleCodes.isEmpty()) {
            // Compatibility fallback for legacy data before RBAC migration.
            String role = (userInfo.getLevel() != null && userInfo.getLevel() >= 1) ? "ADMIN" : "USER";
            roleCodes = List.of(role);
        }
        for (String roleCode : roleCodes) {
            authorities.add(new SimpleGrantedAuthority("ROLE_" + roleCode));
        }

        return new UserInfo(
                authorities,
                userInfo.getId(),
                userInfo.getPassword(), // Must be a BCrypt hash (see V2 migration)
                userInfo.getUsername(),
                userInfo.getPhone()
        );
    }
}
