package com.tasteby.security;

import io.jsonwebtoken.Claims;
import org.springframework.http.HttpStatus;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.server.ResponseStatusException;

/**
 * Utility to extract current user info from SecurityContext.
 */
public final class AuthUtil {

    private AuthUtil() {}

    public static Claims getCurrentUser() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth == null || !(auth.getPrincipal() instanceof Claims)) {
            throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "Not authenticated");
        }
        return (Claims) auth.getPrincipal();
    }

    public static Claims getCurrentUserOrNull() {
        Authentication auth = SecurityContextHolder.getContext().getAuthentication();
        if (auth == null || !(auth.getPrincipal() instanceof Claims)) {
            return null;
        }
        return (Claims) auth.getPrincipal();
    }

    public static Claims requireAdmin() {
        Claims user = getCurrentUser();
        if (!Boolean.TRUE.equals(user.get("is_admin", Boolean.class))) {
            throw new ResponseStatusException(HttpStatus.FORBIDDEN, "관리자 권한이 필요합니다");
        }
        return user;
    }

    public static String getUserId() {
        return getCurrentUser().getSubject();
    }
}
