import 'server-only';
import { NextRequest, NextResponse } from 'next/server';

/**
 * Every /api/cron/* route is a plain HTTP endpoint — there's no dashboard
 * triggering these, so they must be safe to expose publicly and only act
 * for whoever holds CRON_SECRET. Vercel Cron sends this automatically as
 * an Authorization header when configured per vercel.json; a VPS setup
 * should pass it the same way from its scheduler (see README > Deploying
 * to a VPS).
 */
export function assertCronAuthorized(req: NextRequest): NextResponse | null {
  const secret = process.env.CRON_SECRET;
  if (!secret) {
    console.error('[cron] CRON_SECRET is not set — refusing all cron requests until it is configured.');
    return NextResponse.json({ error: 'Server misconfigured: CRON_SECRET not set' }, { status: 500 });
  }

  const header = req.headers.get('authorization');
  if (header !== `Bearer ${secret}`) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  return null;
}
