package com.its.web.service.admin;

import com.its.web.dto.admin.PrincipalDetail;
import com.its.web.dto.admin.TbWwwMemberDto;
import com.its.web.mapper.its.admin.AdminMapper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
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;

@Slf4j
@Service
@RequiredArgsConstructor
public class LoginService implements UserDetailsService {
    private final AdminMapper adminMapper;

    @Override
    public UserDetails loadUserByUsername(String userId) throws UsernameNotFoundException {
        TbWwwMemberDto dto = adminMapper.findMemberWidthId(userId);
        if (dto != null) {
            PrincipalDetail principal = new PrincipalDetail(dto);

//            if (dto.getIpAddress() != null) {
//                String[] ipArray = dto.getIpAddress().split(",");
//                if (ipArray.length > 0) {
//                    List<String> ipList = new ArrayList<>(Arrays.asList(ipArray));
//                    try {
//                        InetAddress ipAddress = InetAddress.getLocalHost();
//                        if (ipList.contains("*") || ipList.contains(ipAddress.getHostAddress())) {
//                            return principal;
//                        }
//                        else {
//                             throw new UsernameNotFoundException("접속 가능 IP를 확인해주세요");
//                        }
//                    } catch (UnknownHostException e) {
//                        log.error("IP 정보를 확인 할수 없습니다.");
//                    }
//                }
//            }
            return principal;
        }
        else {
            throw new UsernameNotFoundException(userId + " 을(를) 찾을 수 없습니다.");
        }
    }
}
