package de.cannamanage.api.security;

import de.cannamanage.domain.entity.StaffAccount;
import de.cannamanage.service.repository.StaffAccountRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.stereotype.Component;

import java.util.UUID;

/**
 * SpEL-accessible bean for checking prevention officer status.
 * Usage in @PreAuthorize:
 *   @PreAuthorize("hasRole('ADMIN') or @preventionOfficer.check(authentication)")
 */
@Slf4j
@Component("preventionOfficer")
@RequiredArgsConstructor
public class PreventionOfficerChecker {

    private final StaffAccountRepository staffAccountRepository;

    /**
     * Checks if the authenticated user is a designated prevention officer.
     * ADMIN always passes. STAFF must have is_prevention_officer = true.
     */
    public boolean check(Authentication authentication) {
        if (authentication == null || !authentication.isAuthenticated()) {
            return false;
        }

        // ADMIN always passes
        boolean isAdmin = authentication.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .anyMatch(a -> a.equals("ROLE_ADMIN"));
        if (isAdmin) {
            return true;
        }

        // STAFF must be a prevention officer
        boolean isStaff = authentication.getAuthorities().stream()
                .map(GrantedAuthority::getAuthority)
                .anyMatch(a -> a.equals("ROLE_STAFF"));
        if (!isStaff) {
            return false;
        }

        UUID userId = (UUID) authentication.getPrincipal();
        return staffAccountRepository.findByUserId(userId)
                .filter(StaffAccount::isActive)
                .map(StaffAccount::isPreventionOfficer)
                .orElse(false);
    }
}
