package com.platform2easy.genesis.domain.service;

import com.platform2easy.genesis.domain.model.AppUser;
import com.platform2easy.genesis.domain.repository.AppUserRepository;
import lombok.AllArgsConstructor;
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 org.springframework.transaction.annotation.Transactional;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;

import java.util.List;
import java.util.Collections;

@Service
@AllArgsConstructor
public class UserService implements UserDetailsService {

    private final AppUserRepository appUserRepository;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        AppUser appUser = appUserRepository.findByUserEmail(username)
                .orElseThrow(() -> new UsernameNotFoundException("User not found: " + username));
        return new User(appUser.getUserEmail(), appUser.getUserPassword(),
                Collections.singletonList(new SimpleGrantedAuthority("ROLE_USER")));
    }

    @Transactional
    public AppUser salvar(AppUser user) {
        return appUserRepository.save(user);
    }

    public List<AppUser> buscarPorEmpresa(Integer companyId) {
        return appUserRepository.findByCompanyId(companyId);
    }

    public List<AppUser> listAll(){
        return appUserRepository.findAll();
    }

    public void deletarPorId(Long id) {
        appUserRepository.deleteById(id);
    }
}