import { NextRequest, NextResponse } from 'next/server'
import { createAdminClient } from '@/lib/supabase/admin'
import { publicOrigin } from '@/lib/app-url'
import { pilotNetworkAvailable, runPilotCampaignsDay } from '@/lib/data/pilot-network'
import { requireInternal } from '../_guard'

/**
 * The scheduler's entry point (answer 5). Called by the host cron with the
 * secret in the `x-pilot-cron-secret` header (PILOT_CRON_SECRET in .env),
 * or by a signed-in internal user. Honours the cron on/off switch; the
 * daily limit is per calendar day so repeated calls are safe.
 */
export async function POST(req: NextRequest) {
  const secret = process.env.PILOT_CRON_SECRET
  const header = req.headers.get('x-pilot-cron-secret')
  let actor = { id: null as string | null, label: 'cron' }
  if (!(secret && header && header === secret)) {
    const guard = await requireInternal()
    if (!guard.ok) return guard.response
    actor = guard.actor
  }
  const admin = createAdminClient()
  if (!(await pilotNetworkAvailable(admin))) return NextResponse.json({ error: 'Migration 0018 not applied.' }, { status: 503 })
  const summary = await runPilotCampaignsDay({ origin: publicOrigin(req), actorId: actor.id, actorLabel: actor.label, manual: false }, admin)
  return NextResponse.json({ ok: true, summary })
}
