package org.openautonomousconnection.webserver.api;

import org.openautonomousconnection.protocol.side.web.ConnectedWebClient;
import org.openautonomousconnection.protocol.side.web.ProtocolWebServer;
import org.openautonomousconnection.protocol.side.web.managers.SessionManager;

import java.io.IOException;
import java.util.Map;

/**
 * Provides session-related information for Java WebPages.
 * Thin layer on top of SessionManager.
 */
public final class SessionContext {

    private final String sessionId;
    private final String user;
    private final boolean valid;

    private SessionContext(String sessionId, String user, boolean valid) {
        this.sessionId = sessionId;
        this.user = user;
        this.valid = valid;
    }

    public static SessionContext from(ConnectedWebClient client, ProtocolWebServer server, Map<String, String> headers) throws IOException {
        if (headers == null) return new SessionContext(null, null, false);

        String sessionId = headers.get("session");
        if (sessionId == null) return new SessionContext(null, null, false);

        String ip = (client.getWebSocket() != null && client.getWebSocket().getInetAddress() != null)
                ? client.getWebSocket().getInetAddress().getHostAddress() : "";

        String userAgent = headers.getOrDefault("user-agent", "");

        boolean valid = SessionManager.isValid(sessionId, ip, userAgent, server);
        if (!valid) return new SessionContext(sessionId, null, false);

        String user = SessionManager.getUser(sessionId);
        return new SessionContext(sessionId, user, true);
    }

    public boolean isValid() { return valid; }
    public String getSessionId() { return sessionId; }
    public String getUser() { return user; }
}
