Files
SpaceWanderer/app/api/ship/build/route.ts
T
2026-10-04 02:34:56 +00:00

46 lines
2.1 KiB
TypeScript

import { getGameDb } from '@/lib/db/client'
import * as schema from '@/lib/db/schema'
import { parseCrewTeam } from '@/app/api/crew-team'
import { checkBuildPreconditions, getShipState, ShipError } from '@/lib/game/ship'
import { makePowerOfFor, queueStateFromSave, saveInventory, saveTaskRow } from '@/lib/game/save'
import { queueTask, TaskError } from '@/lib/game/tasks'
// Build an unbuilt ship system type at base values: assign the crew team (lead + helpers)
// and queue the SHIP_BUILD task — the flat parts cost is deducted at queue time and the
// build lands when the task completes on the turn tick (runTurn). Body:
// { type, leadCrewId, helperCrewIds? }. Queueing spends no turn; returns the same fresh
// ship state the instant action returned.
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 type = (body as { type?: unknown }).type
if (typeof type !== 'string' || type.length === 0) {
return Response.json({ error: 'type must be a non-empty string' }, { 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 checkBuildPreconditions(db, type) // existing pre-checks: 404 unknown type · 409 already built / build gate
const state = await queueStateFromSave(db)
const [save] = await db.db.select().from(schema.saves).limit(1)
const { task, inventory } = queueTask(state, { type: 'SHIP_BUILD', payload: { type }, leadCrewId: team.leadCrewId, helperCrewIds: team.helperCrewIds }, await makePowerOfFor(db, save, 'SHIP_BUILD'))
await saveTaskRow(db, task)
await saveInventory(db, inventory) // the cost was deducted at queue time
return Response.json(await getShipState(db))
} catch (err) {
if (err instanceof ShipError || err instanceof TaskError) {
return Response.json({ error: err.message }, { status: err.status })
}
throw err
}
}