import { NextRequest, NextResponse } from 'next/server';
import { runMonthlyBillingForAll } from '@/lib/billing-service';

/**
 * GET /api/cron/monthly-billing
 *
 * Triggered by Vercel Cron on the 1st of each month at 00:05 UTC.
 * Secured with CRON_SECRET header — Vercel sets this automatically when
 * configured in vercel.json; reject anything without it.
 *
 * Can also be called manually by an admin via POST.
 */
async function handler(request: NextRequest) {
  const cronSecret = process.env.CRON_SECRET;
  const authHeader = request.headers.get('authorization');

  if (!cronSecret || authHeader !== `Bearer ${cronSecret}`) {
    return NextResponse.json({ error: 'Unauthorized' }, { status: 401 });
  }

  try {
    console.log('[cron] Starting monthly billing run...');
    const result = await runMonthlyBillingForAll();
    console.log('[cron] Monthly billing complete:', result);
    return NextResponse.json({
      ok: true,
      processed: result.processed,
      charged: result.charged,
      skipped: result.skipped,
      failed: result.failed,
      noPaymentMethod: result.noPaymentMethod,
    });
  } catch (err) {
    console.error('[cron] Monthly billing failed:', err);
    return NextResponse.json({ error: 'Billing run failed' }, { status: 500 });
  }
}

export { handler as GET, handler as POST };
