package de.cannamanage.api.security;

import de.cannamanage.domain.entity.User;
import de.cannamanage.domain.enums.UserRole;
import de.cannamanage.service.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * UserDetailsService for portal session-based auth.
 * Only loads MEMBER-role users who are active. Members log in by email.
 */
@Service("portalUserDetailsService")
@RequiredArgsConstructor
public class PortalUserDetailsService implements UserDetailsService {

    private final UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String email) throws UsernameNotFoundException {
        User user = userRepository.findByEmail(email)
                .orElseThrow(() -> new UsernameNotFoundException("No user found with email: " + email));

        // Only MEMBER role users may use the portal
        if (user.getRole() != UserRole.ROLE_MEMBER) {
            throw new UsernameNotFoundException("User is not a member");
        }

        // Must be active
        if (!user.isActive()) {
            throw new UsernameNotFoundException("User account is inactive");
        }

        // Must have a linked memberId
        if (user.getMemberId() == null) {
            throw new UsernameNotFoundException("User has no linked member profile");
        }

        var authorities = List.of(new SimpleGrantedAuthority("ROLE_MEMBER"));

        return new PortalPrincipal(
                user.getEmail(),
                user.getPasswordHash(),
                authorities,
                user.getTenantId(),
                user.getMemberId()
        );
    }
}
