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 com.its.web.security.WebPasswordEncoder;
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;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
@RequiredArgsConstructor
public class LoginService implements UserDetailsService {
    private final AdminMapper adminMapper;
    private final WebPasswordEncoder encoder = new WebPasswordEncoder();

    @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 + " 을(를) 찾을 수 없습니다.");
        }
    }

    public Map<String, String> loginCheck(String id, String pwd) {
        Map<String, String> resultMap = new HashMap<>();
        String message = "";
        String success = "S";
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("id", id);
        paramMap.put("pwd", encoder.encode(pwd));
        TbWwwMemberDto dto = this.adminMapper.findMemberWidthId(id);
        String wrongText = "ID 또는 비밀번호를 확인해주세요";
        String lockText = "5회 이상 로그인 실패로 계정 이용 불가<br>관리자에게 문의하세요.";
        if (dto != null) {
            if (dto.getLoginFailCount() == 5 || dto.getIsAccountLock().equals("Y"))  {
                success = "F";
                message = lockText;
            }
            else if (this.adminMapper.findMemberWidthIdPwd(paramMap) <= 0) {
                success = "F";
                message = wrongText;
                paramMap.put("loginFailCount", (dto.getLoginFailCount() + 1) + "");
                if (dto.getLoginFailCount() == 4) {
                    paramMap.put("isAccountLock", "Y");
                    message = lockText;
                }
                this.adminMapper.updateFailCount(paramMap);
            }
        }
        else {
            message = wrongText;
            success = "F";
        }

        if (success.equals("S")) {
            paramMap.put("isAccountLock", "N");
            paramMap.put("loginFailCount", "0");
            this.adminMapper.updateFailCount(paramMap);
        }
        resultMap.put("message", message);
        resultMap.put("success", success);
        return resultMap;
    }
}
