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

import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

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

@Slf4j
@RequiredArgsConstructor
@Controller
public class PublicApiController {
    private final PasswordEncoder passwordEncoder;

    /**
     * 암호화 문자열을 만들기 위한 API
     * @param paramMap {"password": "평문 문자열"}
     * @return {"password": "암호화 문자열"}
     */
    @RequestMapping(value = "/public-api/passwordGenerator")
    public ResponseEntity<?> passwordGenerator(Map<String, String> paramMap) {
        Map<String, String> resultMap = new HashMap<>();
        String plainPassword = paramMap.get("password");
        if(StringUtils.isNotEmpty(plainPassword)) {
            String encryptedPassword = passwordEncoder.encode(plainPassword);
            resultMap.put("password", encryptedPassword);
        }
        else {
            resultMap.put("password", "");
        }
        return ResponseEntity.ok(resultMap);
    }

    /**
     * 로그인 세션을 확인하기 위한 API
     * @param userDetails DI 주입
     * @return {"success": true/false, "username": 사용자 아이디}
     */
    @RequestMapping(value = "/public-api/sessionCheck")
    public ResponseEntity<?> sessionCheck(@AuthenticationPrincipal UserDetails userDetails) {
        Map<String, Object> resultMap = new HashMap<>();
        if(userDetails != null) {
            resultMap.put("success", true);
            resultMap.put("username", userDetails.getUsername());
        }
        else {
            resultMap.put("success", false);
            resultMap.put("username", "");
        }
        return ResponseEntity.ok(resultMap);
    }
}
