package com.bsmlab.dfx.dfxconsole.framework.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.FilterChain;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.AuthenticationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RequiredArgsConstructor
public class JsonUsernamePasswordAuthenticationFilter extends UsernamePasswordAuthenticationFilter {
    ObjectMapper objectMapper = new ObjectMapper();
    @SuppressWarnings("unchecked")
    @Override
    public Authentication attemptAuthentication(HttpServletRequest request, HttpServletResponse response) throws AuthenticationException {
        if(!request.getContentType().equals(MediaType.APPLICATION_JSON_VALUE)) {
            throw new IllegalArgumentException("not application/json");
        }
        try {
            Map<String, String> userInfoMap = objectMapper.readValue(request.getInputStream(), Map.class);
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(userInfoMap.get("username"), userInfoMap.get("password"));
            this.setDetails(request, usernamePasswordAuthenticationToken);
            return this.getAuthenticationManager().authenticate(usernamePasswordAuthenticationToken);
        }
        catch(IOException e) {
            throw new AuthenticationServiceException("사용자 정보를 확인할 수 없습니다.");
        }
    }

    // 로그인 성공 후 결과 메시지 전달. 자동 호출됨.
    @Override
    protected void successfulAuthentication(HttpServletRequest request, HttpServletResponse response, FilterChain chain, Authentication authResult) throws IOException {
        log.info("로그인 성공: {}", authResult.getName());
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/json");
        Map<String, Object> result = new HashMap<>();
        result.put("success", true);
        result.put("username", authResult.getName());
        objectMapper.writeValue(response.getWriter(), result);
    }

    // 로그인 실패 후 결과 메시지 전달. 자동 호출됨.
    @Override
    protected void unsuccessfulAuthentication(HttpServletRequest request, HttpServletResponse response, AuthenticationException failed) throws IOException {
        log.warn("로그인 실패: {}", failed.getMessage());
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        response.setContentType("application/json");
        Map<String, Object> result = new HashMap<>();
        result.put("success", false);
        result.put("message", "인증에 실패했습니다.");
        objectMapper.writeValue(response.getWriter(), result);
    }
}
