package de.oaa.xxx.framework.request;

import java.net.URI;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.ws.rs.client.Client;
import jakarta.ws.rs.client.ClientBuilder;
import jakarta.ws.rs.core.Response;
import jakarta.ws.rs.core.Response.Status;

public class RequestChecker {

	public static User checkRequest(HttpServletRequest request) throws NotAuthorizedException {
		String token = request.getHeader("token");
		if (token == null) {
			throw new NotAuthorizedException("Kein Token im Header");
		}
		Client clientPost = ClientBuilder.newClient();
		Response response = 
				clientPost.target("http://localhost:8080/user-service/login/")
				.queryParam("token", token).request().build("POST").invoke();
		if (response == null || Status.CREATED.getStatusCode() != response.getStatus()) {
			throw new NotAuthorizedException("Token konnte nicht validiert werden.");
		}
		URI uri = response.getLocation();
		clientPost.close();
		Client clientGet = ClientBuilder.newClient();
		User result = clientGet.target(uri).request().get(User.class);
		clientGet.close();
		return result;
	}
}
