package de.oaa.xxx.games.chastity.ttlock;

import java.util.Map;

import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

@Service
public class TTAuthService {

	private final String AUTH_URL = "https://euapi.ttlock.com/oauth2/token";

    @SuppressWarnings("unchecked")
	public String getAccessToken(String clientId, String clientSecret, String username, String md5Password) {
        RestTemplate restTemplate = new RestTemplate();
        
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);

        MultiValueMap<String, String> map = new LinkedMultiValueMap<>();
        map.add("client_id", clientId);
        map.add("client_secret", clientSecret);
        map.add("username", username);
        map.add("password", md5Password); // MD5 Hash des TTLock-Passworts
        map.add("grant_type", "password");

        HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(map, headers);
        
        // Response parsen und access_token extrahieren
        Map<String, Object> response = restTemplate.postForObject(AUTH_URL, request, Map.class);
        return (String) response.get("access_token");
    }
}
