package com.example.domain;

import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import lombok.extern.slf4j.Slf4j;

//ユーザーの認証・認可にかかわるクラス
@Slf4j
public class LoginUser extends org.springframework.security.core.userdetails.User{
	
	private static final long serialVersionUID = 1L;
	private User user;
	
	public LoginUser(User user){
		super(user.getEmail(), user.getPassword(), convertGrantedAuthorities(user.getRoles()));
		this.user = user;
	}
	
	public User getUser() {
		return user;
	}
	
	
	static Set<GrantedAuthority> convertGrantedAuthorities(String roles){
		if(roles == null || roles.isEmpty()){
			return Collections.emptySet();
		}
		Set<GrantedAuthority> authorities = Stream.of(roles.split(","))
				.map(SimpleGrantedAuthority::new)
				.collect(Collectors.toSet());
		return authorities;
	}
}
