package tech.nevets.tvpn.auth;

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import tech.nevets.tvpn.Logger;
import tech.nevets.tvpn.Utils;

import java.io.IOException;
import java.net.URI;
import java.net.http.HttpRequest;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;

public class AuthManager {

    private static final Logger LOGGER = new Logger(AuthManager.class);

    public static UserToken httpAuth(String username, String password) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        String body = "{" +
                "\"username\":\"" + username + "\"," +
                "\"password\":\"" + password + "\"" +
                "}";
        String res = Utils.post(URI.create(Utils.API_ENDPOINT_BASE + "api/auth.php"), headers, HttpRequest.BodyPublishers.ofString(body));
        JsonObject resObj = new Gson().fromJson(res, JsonObject.class);
        UserToken token = new UserToken(resObj.get("isAuthenticated").getAsBoolean(), resObj.get("token").getAsString(), resObj.get("expires").getAsLong(), resObj.get("message").getAsString());

        try {
            if (token.getToken().isEmpty()) return token;
            Files.writeString(Path.of(Utils.APP_DIR + "/token.txt"), token.getToken());
        } catch (IOException e) {
            LOGGER.error(e.getMessage());
        }

        return token;
    }

    public static UserToken checkAuth() {
        try {
            String token = Files.readString(Path.of(Utils.APP_DIR + "/token.txt"));
            Map<String, String> headers = new HashMap<>();
            headers.put("Authorization", "Bearer " + token);
            String res = Utils.get(URI.create(Utils.API_ENDPOINT_BASE + "api/auth.php"), headers);
            JsonObject resObj = new Gson().fromJson(res, JsonObject.class);
            return new UserToken(resObj.get("isAuthenticated").getAsBoolean(), resObj.get("token").getAsString(), resObj.get("expires").getAsLong(), resObj.get("message").getAsString());
        } catch (IOException e) {
            System.out.println("No token file found");
            return new UserToken(false, "", 0, e.getMessage());
        }
    }

}
