import { NextRequest, NextResponse } from 'next/server'
import { z } from 'zod'
import { createAdminClient } from '@/lib/supabase/admin'
import { logPilotNetworkAction, pilotNetworkAvailable } from '@/lib/data/pilot-network'
import { migrationMissing, requireInternal } from '../_guard'

/** Answer 5: the cron switch — on, it runs continuously; off, the scheduler's calls do nothing. */
const schema = z.object({ cron_enabled: z.boolean() })

export async function POST(req: NextRequest) {
  const guard = await requireInternal()
  if (!guard.ok) return guard.response
  const parsed = schema.safeParse(await req.json().catch(() => ({})))
  if (!parsed.success) return NextResponse.json({ error: 'Invalid request.' }, { status: 400 })
  const admin = createAdminClient()
  if (!(await pilotNetworkAvailable(admin))) return migrationMissing()
  await admin.from('pilot_network_settings').upsert({ id: 1, cron_enabled: parsed.data.cron_enabled, updated_by: guard.actor.label, updated_at: new Date().toISOString() }, { onConflict: 'id' })
  await logPilotNetworkAction({ actorId: guard.actor.id, actorLabel: guard.actor.label, action: parsed.data.cron_enabled ? 'cron_turned_on' : 'cron_turned_off', entityType: 'setting', entityId: 'cron' }, admin)
  return NextResponse.json({ ok: true })
}
