import { createGenesisAuth } from "../auth/index.js";
import { isAnonymousAuthResult } from "../auth/types.js";
/**
 * Vercel / Edge middleware helper. Returns a response to short-circuit, or request/identity to continue.
 *
 * ```ts
 * const auth = genesisAuthVercel({ projectId });
 * export async function middleware(request: Request) {
 *   const result = await auth(request);
 *   if (result.response) return result.response;
 *   return NextResponse.next({ request: result.request ?? request });
 * }
 * ```
 */
export function genesisAuthVercel(config) {
    const auth = createGenesisAuth(config);
    return async (request) => {
        const result = await auth.authenticate(request);
        if (!result.ok) {
            if (isAnonymousAuthResult(result)) {
                return { request: stripGenesisHeaders(request) };
            }
            return { response: new Response(result.message, { status: result.status }) };
        }
        return {
            identity: result.identity,
            request: attachGenesisIdentityHeaders(request, result.identity),
        };
    };
}
function stripGenesisHeaders(request) {
    const headers = new Headers();
    for (const [key, value] of request.headers) {
        if (!key.toLowerCase().startsWith('x-genesis-')) {
            headers.set(key, value);
        }
    }
    return new Request(request, { headers });
}
export function attachGenesisIdentityHeaders(request, identity) {
    const headers = new Headers();
    for (const [key, value] of request.headers) {
        if (!key.toLowerCase().startsWith('x-genesis-')) {
            headers.set(key, value);
        }
    }
    headers.set('x-genesis-user-id', identity.userId);
    headers.set('x-genesis-genesis-user-id', identity.genesisUserId);
    if (identity.email) {
        headers.set('x-genesis-user-email', identity.email);
    }
    return new Request(request, { headers });
}
//# sourceMappingURL=vercel.js.map