package com.oqpo.api.service;

import com.oqpo.api.config.JwtTokenProvider;
import com.oqpo.api.constant.ApiConstants;
import com.oqpo.api.entity.oper.MemberEntity;
import com.oqpo.api.enums.SystemMessageCode;
import com.oqpo.api.exception.GlobalException;
import com.oqpo.api.mapper.MemberMapper;
import com.oqpo.api.mapper.oper.UserMngMapper;
import com.oqpo.api.service.oper.UserMngService;
import com.oqpo.api.util.StringUtil;
import com.oqpo.api.web.dto.response.oper.usermng.UserInfoResponse;
import com.oqpo.api.web.dto.response.session.FindIdResponse;
import com.oqpo.api.web.dto.response.session.FindPwResponse;
import com.oqpo.api.web.dto.response.token.JwtResponse;
import com.oqpo.api.web.dto.response.token.TokenResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.logout.SecurityContextLogoutHandler;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

@Service
@Slf4j
public class SigninService implements UserDetailsService {
    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtTokenProvider jwtTokenProvider;

    @Autowired
    private UserMngService userMngService ;


    public JwtResponse signin(String userId, String password) throws Exception {
        MemberEntity memberEntity = null;
        String connKey = "";
        try {
            UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(userId, password);
            Authentication authentication = authenticationManager.authenticate(token);
            SecurityContextHolder.getContext().setAuthentication(authentication);
            memberEntity = (MemberEntity) authentication.getPrincipal();

            connKey = jwtTokenProvider.createToken (
                    memberEntity.getUserId(),
                    memberEntity.getUserNm(),
                    memberEntity.getSystemAdminYn(),
                    memberEntity.getAuthTpCd(),
                    true,
                    memberEntity.getAfflShopId(),
                    memberEntity.getBrandId(),
                    memberEntity.getAuthTpNm());
            log.debug("connKey==>>>{}", connKey);

            //로그인 이력 남기기
            userMngService.updateLoginDt(memberEntity.getUserId());

        } catch (Exception e) {
            e.getStackTrace();
            throw new GlobalException(SystemMessageCode.SIGNIN_FAIL);
        }
        return JwtResponse.toDTO(connKey);
    }

    public void logout(HttpServletRequest request, HttpServletResponse response) throws Exception {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth != null) {
            new SecurityContextLogoutHandler().logout(request, response, auth);
        }
    }

    public UserDetails getMember(String userId) {
        MemberEntity entity = memberMapper.selectMemberById(userId);
        entity.setAuthorities(getAuthorities());
        return entity;
    }

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        return getMember(username);
    }

    public Collection<GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>();
        authorities.add(new SimpleGrantedAuthority("ROLE_SRM_MEMBER"));
        return authorities;
    }

    public PasswordEncoder passwordEncoder() {
        return this.passwordEncoder;
    }

    public FindIdResponse selectMemberFindId(String userNm, String email, String telNo) {
        MemberEntity entity = memberMapper.selectMemberFindId(userNm, email, telNo);

        if (entity == null) {
            throw new GlobalException(SystemMessageCode.ERR_FIND_ID);
        }

        return FindIdResponse.toDTO(entity);
    }

    public FindPwResponse selectMemberFindPw(String userId, String email, String telNo) throws Exception {
        String newpw = "";
        MemberEntity entity = new MemberEntity() ;
        int idCnt = memberMapper.selectMemberFindPwCnt(userId, email, telNo);

        if (idCnt == 0) {
            throw new GlobalException(SystemMessageCode.ERR_FIND_PW);
        } else {
            newpw = StringUtil.makeSecureString(6) ;
            entity.setUserId(userId);
            entity.setPassword(newpw);

            //패스워드 변경처리함
            userMngService.updateChgUserPw(userId, newpw);
        }

        return FindPwResponse.toDTO(entity);
    }




}
