import { Archon } from "../Archon.js";
import { AccessDetermination, ArchonResourceId, Resource, ResourceIntent, ResourceIntentName } from "../types/policy.js";
import { Session, SessionId } from "../types/user.js";

/**
 * Given a user session and a resource, determine if the user has access to the resource with the given intent.
 * This function contacts the Archon policy service to determine access. To edit policies or add new ones,
 * log into the dashboard and initiate a change.
 * @param session The session of the user attempting to access the resource.
 * @param resource The resource being accessed, identified by its ARID.
 * @param intent The intent with which the user is attempting to access the resource.
 * @returns Whether the user has access to the resource with the given intent.
 */
export default async function determineAccess(session: Session | SessionId, resource: Resource | ArchonResourceId, intent: ResourceIntent | ResourceIntentName): Promise<AccessDetermination> {
    const arid = typeof resource === "string" ? resource : resource.arid;
    const response = await Archon.request(`/policy/access/${arid}`, "POST", {
        sessionId: typeof session === "number" ? session : session.id,
        intentName: typeof intent === "string" ? intent : intent.name
    });

    if (response.status !== 200) {
        throw new Error(`Failed to determine access: ${response.data}`);
    }

    return {
        allowed: response.data.allowed,
        reason: "",
        accessibleVia: response.data.accessibleVia
    }
}