package com.spring.infra.security.domain;

import java.util.Arrays;
import java.util.Collection;
import java.util.stream.Collectors;

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

import com.spring.domain.user.entity.AgentUser;
import com.spring.domain.user.entity.AgentUserRole;

import lombok.Getter;
import lombok.RequiredArgsConstructor;

@Getter
@RequiredArgsConstructor
public class UserPrincipal implements UserDetails {

    private final transient AgentUser agentUser;

    public static UserPrincipal valueOf(AgentUser agentUser) {
        return new UserPrincipal(agentUser);
    }

    public static UserPrincipal of(String userId, String userName) {
        return new UserPrincipal(AgentUser.builder().userId(userId).name(userName).build());
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return Arrays.stream(AgentUserRole.values())
            .filter(role -> Arrays.asList(agentUser.getUserRole()).contains(role)) 
            .map(AgentUserRole::getRole)
            .map(SimpleGrantedAuthority::new)
            .collect(Collectors.toList());
    }

    @Override
	public boolean isAccountNonExpired() {
		return true;
	}

	@Override
	public boolean isAccountNonLocked() {
		return true;
	}

	@Override
	public boolean isCredentialsNonExpired() {
		return true;
	}

	@Override
	public boolean isEnabled() {
		return true;
	}

    @Override
    public String getPassword() {
        return agentUser.getPassword();
    }

    @Override
    public String getUsername() {
        return agentUser.getUserId();
    }

    public String getKey() {
        return agentUser.getId().toString();
    }

    public String getMemberName() {
        return agentUser.getName();
    }

}
