package com.gnx.telemedicine.security;

import com.gnx.telemedicine.model.UserModel;
import com.gnx.telemedicine.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
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;

@Service
@RequiredArgsConstructor
public class CustomUserDetailsService implements UserDetailsService {
    private final UserRepository userRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        UserModel user = userRepository.findByEmail(username).orElseThrow(() ->
                new UsernameNotFoundException("User not found"));

        // Check if user account is active
        boolean isEnabled = Boolean.TRUE.equals(user.getIsActive());
        
        return new User(user.getEmail(),
                user.getPassword(),
                isEnabled, // account enabled/disabled based on isActive
                true, // accountNonExpired
                true, // credentialsNonExpired
                true, // accountNonLocked
                List.of(new SimpleGrantedAuthority("ROLE_" + user.getRole().name())));
    }
}
