package com.samsung.interceptor;

import com.samsung.authentication.Account;
import com.samsung.core.exception.PrivacyPolicyException;
import com.samsung.user.entity.User;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

@Log4j2
public class PrivacyPolicyInterceptor implements HandlerInterceptor {

    /**
     * 약관동의 사용 여부
     */
    @Value("${privacy-policy.check.enabled:true}")
    private boolean privacyPolicyCheck;

    /**
     * 약관동의 인터셉터 체크 제외 URI
     */
    @Value("${privacy-policy.check.exclude-path}")
    private String privacyPolicyCheckExcludePath;

    @Override
    @SuppressWarnings("squid:S3516")
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        if (!privacyPolicyCheck) return true;

        String requestUri = request.getRequestURI();
        String[] privacyPolicyCheckExcludePathList = privacyPolicyCheckExcludePath.split(",");
        for (String excludePath : privacyPolicyCheckExcludePathList) {
            if (requestUri.contains(excludePath)) {
                return true;
            }
        }

        User user = Account.currentUser();

        if (user != null && !user.isPrivacyPolicy()) {
            throw new PrivacyPolicyException("Privacy policy agreement required.");
        } else {
            return true;
        }
    }
}
