package com.kamco.cd.training.common.utils;

import com.kamco.cd.training.auth.CustomUserDetails;
import com.kamco.cd.training.members.dto.MembersDto;
import com.kamco.cd.training.postgres.entity.MemberEntity;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

@Component
@RequiredArgsConstructor
public class UserUtil {

  public MembersDto.Member getCurrentUser() {
    return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
        .filter(auth -> auth.getPrincipal() instanceof CustomUserDetails)
        .map(
            auth -> {
              CustomUserDetails user = (CustomUserDetails) auth.getPrincipal();
              MemberEntity m = user.getMember();
              return new MembersDto.Member(m.getId(), m.getName(), m.getEmployeeNo());
            })
        .orElse(null);
  }

  public Long getId() {
    MembersDto.Member user = getCurrentUser();
    return user != null ? user.getId() : null;
  }

  public String getName() {
    MembersDto.Member user = getCurrentUser();
    return user != null ? user.getName() : null;
  }

  public String getEmployeeNo() {
    MembersDto.Member user = getCurrentUser();
    return user != null ? user.getEmployeeNo() : null;
  }
}
