import { getGameDb } from '@/lib/db/client' import * as schema from '@/lib/db/schema' import { parseCrewTeam } from '@/app/api/crew-team' import { checkExploreTarget, ExploreError, getSystemState, makePowerOfFor, queueStateFromSave, saveTaskRow } from '@/lib/game/save' import { queueTask, TaskError } from '@/lib/game/tasks' // Scan one body of the current system: assign the crew team (lead + helpers) and queue the // EXPLORE task — the haul, the scanned flag, the crew roll and the event land when the task // completes on the turn tick (runTurn). Body: { planetId, leadCrewId, helperCrewIds? }. // Queueing spends no turn; returns the same system snapshot as the instant scan, with the // findings key empty until the scan resolves (JC-2). export async function POST(req: Request) { let body: unknown try { body = await req.json() } catch { return Response.json({ error: 'Invalid JSON body' }, { status: 400 }) } const planetId = (body as { planetId?: unknown }).planetId if (typeof planetId !== 'number' || !Number.isInteger(planetId)) { return Response.json({ error: 'planetId must be an integer' }, { status: 400 }) } const team = parseCrewTeam(body) if ('error' in team) { return Response.json({ error: team.error }, { status: team.status }) } try { const db = await getGameDb() await checkExploreTarget(db, planetId) // existing pre-checks: 404 unknown body · 409 already scanned const state = await queueStateFromSave(db) const [save] = await db.db.select().from(schema.saves).limit(1) const { task } = queueTask(state, { type: 'EXPLORE', payload: { planetId }, leadCrewId: team.leadCrewId, helperCrewIds: team.helperCrewIds }, await makePowerOfFor(db, save, 'EXPLORE')) await saveTaskRow(db, task) // inventory is unchanged until the scan resolves — no hold write return Response.json({ ...(await getSystemState(db)), outcome: [], crewFound: null }) } catch (err) { if (err instanceof ExploreError || err instanceof TaskError) { return Response.json({ error: err.message }, { status: err.status }) } throw err } }