import { returnResponse } from '../_util';
import { verifySignature } from '../signature';
import { tagRoute } from './_route-meta';
export function cron(_schedule, optionsOrHandler, maybeHandler) {
    let options;
    let handler;
    if (typeof optionsOrHandler === 'function') {
        // Deprecated: cron(schedule, handler) - defaults to auth: false
        options = { auth: false };
        handler = optionsOrHandler;
    }
    else {
        // New: cron(schedule, options, handler)
        options = optionsOrHandler;
        handler = maybeHandler;
    }
    const cronHandler = async (c) => {
        if (c.req.method !== 'POST') {
            throw new Error(`Cron endpoint must use POST method, but received ${c.req.method}. ` +
                `Use router.post() instead of router.${c.req.method.toLowerCase()}().`);
        }
        if (options.auth) {
            // Clone the request to read body for signature verification without consuming it
            const clonedReq = c.req.raw.clone();
            const body = await clonedReq.text();
            // Verify the cron signature
            const isValid = await verifySignature(c.req.header('X-Agentuity-Cron-Signature'), c.req.header('X-Agentuity-Cron-Timestamp'), body);
            if (!isValid) {
                return c.json({ error: 'Unauthorized' }, 401);
            }
        }
        let result = handler(c);
        if (result instanceof Promise) {
            result = await result;
        }
        if (result instanceof Response) {
            return result;
        }
        return returnResponse(c, result);
    };
    return tagRoute(cronHandler, { type: 'cron', schedule: _schedule });
}
//# sourceMappingURL=cron.js.map