package de.szut.casino.user;

import java.util.Optional;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import de.szut.casino.user.dto.CreateUserDto;
import de.szut.casino.user.dto.GetUserDto;
import de.szut.casino.user.dto.KeycloakUserDto;

@Service
public class UserService {
    @Autowired
    private UserRepository userRepository;

    @Autowired
    private RestTemplate http;

    @Autowired
    private UserMappingService mappingService;

    public UserEntity createUser(CreateUserDto createUserDto) {
        UserEntity user = mappingService.mapToUserEntity(createUserDto);
        userRepository.save(user);

        return user;
    }

    public GetUserDto getUser(String keycloakId) {
        Optional<UserEntity> user = this.userRepository.findOneByKeycloakId(keycloakId);

        return user.map(userEntity -> mappingService.mapToGetUserDto(userEntity)).orElse(null);
    }

    public GetUserDto getCurrentUser(String token) {
        KeycloakUserDto userData = getKeycloakUserInfo(token);

        if (userData == null) {
            return null;
        }
        Optional<UserEntity> user = this.userRepository.findOneByKeycloakId(userData.getSub());

        return user.map(userEntity -> mappingService.mapToGetUserDto(userEntity)).orElse(null);

    }

    private KeycloakUserDto getKeycloakUserInfo(String token) {
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", token);
        ResponseEntity<KeycloakUserDto> response = this.http.exchange("http://localhost:9090/realms/LF12/protocol/openid-connect/userinfo", HttpMethod.GET, new HttpEntity<>(headers), KeycloakUserDto.class);
    
        return response.getBody();
    }

    public boolean exists(String keycloakId) {
        return userRepository.existsByKeycloakId(keycloakId);
    }
}
