import { NextRequest, NextResponse } from 'next/server';
import { assertCronAuthorized } from '@/lib/cron/auth';
import { withJobRun } from '@/lib/cron/jobRun';
import { fetchAndIngestRss } from '@/lib/rss/ingest';

export const runtime = 'nodejs';
export const maxDuration = 120;

export async function POST(req: NextRequest) {
  const authError = assertCronAuthorized(req);
  if (authError) return authError;

  const outcome = await withJobRun('fetch-rss', async () => {
    const result = await fetchAndIngestRss();
    return {
      itemsSeen: result.itemsSeen,
      itemsOk: result.itemsStored,
      itemsFailed: result.errors.length,
      detail: { itemsLinked: result.itemsLinked, errors: result.errors },
    };
  });

  return NextResponse.json(outcome);
}

// Vercel Cron invokes scheduled routes with GET; scripts/run-cron.ts (for
// VPS/manual use) uses POST. Both are accepted and do the same thing.
export const GET = POST;
