package com.petshop.backend.util;

import com.petshop.backend.entity.User;
import com.petshop.backend.repository.UserRepository;
import com.petshop.backend.security.AppPrincipal;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

@Component
public class AuthenticationHelper {

    public static Authentication getAuthentication() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new RuntimeException("No authenticated user found");
        }
        return authentication;
    }

    public static AppPrincipal getAuthenticatedPrincipal() {
        Object principal = getAuthentication().getPrincipal();
        if (principal instanceof AppPrincipal appPrincipal) {
            return appPrincipal;
        }
        throw new RuntimeException("Authenticated principal is not supported");
    }

    public static Long getAuthenticatedUserId() {
        return getAuthenticatedPrincipal().getUserId();
    }

    public static User getAuthenticatedUser(UserRepository userRepository) {
        Authentication authentication = getAuthentication();
        Object principal = authentication.getPrincipal();

        if (principal instanceof AppPrincipal appPrincipal) {
            return userRepository.findById(appPrincipal.getUserId())
                    .orElseThrow(() -> new RuntimeException("User not found: " + appPrincipal.getUserId()));
        }

        String username = authentication.getName();
        return userRepository.findByUsername(username)
                .orElseThrow(() -> new RuntimeException("User not found: " + username));
    }
}
