package eu.mhsl.minenet.minigames.api;

import eu.mhsl.minenet.minigames.Main;
import eu.mhsl.minenet.minigames.api.routes.closeRoom.CloseRoom;
import eu.mhsl.minenet.minigames.api.routes.createRoom.CreateRoom;
import eu.mhsl.minenet.minigames.api.routes.queueRoom.QueueRoom;
import org.spongepowered.configurate.ConfigurationNode;

import static spark.Spark.*;

public class HttpServer {
    private static final ConfigurationNode apiConfig = Main.globalConfig.node("api");
    public HttpServer() {
        if(!apiConfig.node("enabled").getBoolean()) return;

        port(apiConfig.node("port").getInt());
        initExceptionHandler(e -> e.printStackTrace(System.err));
        exception(Exception.class, (exception, request, response) -> {
            exception.printStackTrace(System.err);
            response.status(500);
        });

        before((request, response) -> {
            String userKey = request.headers("Authorization");
            String serverKey = apiConfig.node("secret").getString();
            if(userKey != null && !userKey.equals(serverKey)) {
                halt(401, "Authorization header missing or wrong");
            }
        });

        post("/room", new CreateRoom());
        delete("/room", new CloseRoom());
        post("/queueRoom", new QueueRoom());
    }
}
