package dev.crucifixbeta.mod.commands.impl;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import java.io.IOException;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.net.http.HttpRequest.BodyPublishers;
import java.net.http.HttpRequest.Builder;
import java.net.http.HttpResponse.BodyHandlers;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import net.fabricmc.api.EnvType;
import net.fabricmc.api.Environment;

@Environment(EnvType.CLIENT)
public final class TokenLoginApi {
   private static final String PROFILE_URL;
   private static final HttpClient CLIENT;

   private TokenLoginApi() {
   }

   public static TokenLoginApi.Profile profile(String token) throws IOException, InterruptedException {
      HttpRequest var1 = base("https://api.minecraftservices.com/minecraft/profile", token).GET().build();
      HttpResponse var2 = CLIENT.send(var1, BodyHandlers.ofString(StandardCharsets.UTF_8));
      if (var2.statusCode() != 200) {
         throw new IOException("Profile request failed: " + var2.statusCode());
      } else {
         JsonObject var3 = JsonParser.parseString((String)var2.body()).getAsJsonObject();
         return new TokenLoginApi.Profile(var3.get("id").getAsString(), var3.get("name").getAsString());
      }
   }

   public static int changeName(String token, String newName) throws IOException, InterruptedException {
      HttpRequest var2 = base("https://api.minecraftservices.com/minecraft/profile/name/" + newName, token).PUT(BodyPublishers.noBody()).build();
      return CLIENT.send(var2, BodyHandlers.discarding()).statusCode();
   }

   public static int changeSkin(String token, String skinUrl) throws IOException, InterruptedException {
      String var2 = skinUrl.replace("\\", "\\\\").replace("\"", "\\\"");
      String var3 = "{\"variant\":\"classic\",\"url\":\"" + var2 + "\"}";
      HttpRequest var4 = base("https://api.minecraftservices.com/minecraft/profile/skins", token)
         .header("Content-Type", "application/json")
         .POST(BodyPublishers.ofString(var3, StandardCharsets.UTF_8))
         .build();
      return CLIENT.send(var4, BodyHandlers.discarding()).statusCode();
   }

   private static Builder base(String url, String token) {
      return HttpRequest.newBuilder(URI.create(url))
         .timeout(Duration.ofSeconds(20L))
         .header("User-Agent", "CrucifiX")
         .header("Accept", "application/json")
         .header("Authorization", "Bearer " + token);
   }

   static {

      PROFILE_URL = "https://api.minecraftservices.com/minecraft/profile";
      CLIENT = HttpClient.newBuilder().connectTimeout(Duration.ofSeconds(12L)).build();
   }
@Environment(EnvType.CLIENT)
   public static record Profile(String id, String name) {
   }
}
