package library.routes;

import java.util.Optional;

import io.javalin.http.Context;
import io.javalin.http.ForbiddenResponse;
import library.domain.Member;

/**
 * Small helpers the routes and the filter share.
 */
public final class Auth {

	// Key AuthFilter stores the current member under: ctx.attribute(Auth.MEMBER)
	public static final String MEMBER = "member";

	private static final String BEARER = "Bearer ";

	private Auth() {
	}

	// The token from "Authorization: Bearer <token>", if the header is there
	public static Optional<String> bearerToken(Context ctx) {
		String header = ctx.header("Authorization");
		if (header == null || !header.startsWith(BEARER)) {
			return Optional.empty();
		}
		return Optional.of(header.substring(BEARER.length()));
	}

	// The logged-in member. AuthFilter has already run, so on a protected route
	// this is never null.
	public static Member currentMember(Context ctx) {
		return ctx.attribute(MEMBER);
	}

	// For whole-endpoint rules: 403 unless the current member has this role
	public static Member requireRole(Context ctx, String role) {
		Member current = currentMember(ctx);
		if (!current.role().equals(role)) {
			throw new ForbiddenResponse(); // logged in, but not allowed
		}
		return current;
	}
}
