import { createMiddleware } from 'hono/factory';
import { createGenesisAuth, isGenesisAuthError, requireGenesisIdentity, } from "../auth/index.js";
import { isAnonymousAuthResult } from "../auth/types.js";
export function genesisAuth(config) {
    const auth = createGenesisAuth(config);
    return createMiddleware(async (c, next) => {
        if (config.optional) {
            const result = await auth.authenticate(c.req.raw);
            if (result.ok) {
                c.set('genesisIdentity', result.identity);
            }
            else if (!isAnonymousAuthResult(result)) {
                return c.json({ error: result.message }, result.status);
            }
            await next();
            return;
        }
        try {
            const identity = await requireGenesisIdentity(auth, c.req.raw);
            c.set('genesisIdentity', identity);
            await next();
        }
        catch (err) {
            if (isGenesisAuthError(err)) {
                return c.json({ error: err.message }, err.status);
            }
            return c.json({ error: 'unauthorized' }, 401);
        }
    });
}
//# sourceMappingURL=hono.js.map