import { NextRequest, NextResponse } from "next/server"; import config from "@payload-config"; import { getPayload } from "payload"; import type { GameStructure, Map as MapDoc, Shipment } from "@/payload-types"; import { effectiveMaxMass } from "@/lib/base/modules"; import { aggregateCompoundStorage, compoundParentId, isOperationalMember, } from "@/lib/map/compounds"; import { isPointArray, type MapPoint } from "@/lib/map/points"; import { gridConfigFromMapDoc } from "@/lib/map/grid"; import type { MapFeaturesResponse, StructureFeature } from "@/lib/map/types"; import { listMapObjectives } from "@/lib/map/objectives"; import { hasPermission } from "@/utils/access-control/hasPermission"; export const dynamic = "force-dynamic"; export const runtime = "nodejs"; /** * PostGIS point fields read back as a FLAT [x, y] tuple (not an array of * tuples like the JSON feature geometry). */ function pointOf(coordinates: unknown): MapPoint | null { if (!Array.isArray(coordinates) || coordinates.length !== 2) return null; const x = coordinates[0]; const y = coordinates[1]; if ( typeof x !== "number" || typeof y !== "number" || !Number.isFinite(x) || !Number.isFinite(y) ) { return null; } return [x, y]; } function relationshipId(value: unknown): number | null { if (typeof value === "number") return value; if (value && typeof value === "object" && "id" in value) return (value as { id: number }).id; return null; } /** * View-surface feature feed for the map page (settled decision 8): any * logged-in user may read map features here, while maps/road/zone/node * configuration stays maps:*-gated in the Payload admin panel. */ export async function GET(req: NextRequest) { const payload = await getPayload({ config: await config }); const { user } = await payload.auth({ headers: req.headers, canSetHeaders: false }); if (!user) { return NextResponse.json({ error: "Unauthorized" }, { status: 401 }); } const mapId = Number(req.nextUrl.searchParams.get("mapId")); if (!Number.isInteger(mapId) || mapId <= 0) { return NextResponse.json({ error: "mapId is required" }, { status: 400 }); } const map = await payload .findByID({ collection: "maps", id: mapId, depth: 1, overrideAccess: true }) .catch(() => null); if (!map) { return NextResponse.json({ error: "Map not found" }, { status: 404 }); } const mapDoc = map as unknown as MapDoc & { basemapImage: { url?: string | null } | number | null; }; const worldW = Number(mapDoc.worldSizeWidth ?? 8192); const worldH = Number(mapDoc.worldSizeHeight ?? 8192); // layers=base: basemap + roads + zones only (mission planning maps). Skips // the logistics queries (structures/nodes/shipments) entirely. Objectives are // cheap and belong to every surface, so they are always included. const baseOnly = req.nextUrl.searchParams.get("layers") === "base"; const includeRedacted = await hasPermission(payload, user, "system:admin-access"); const none = { docs: [] as never[] }; const [structuresRes, nodesRes, roadsRes, zonesRes, shipmentsRes, objectives] = await Promise.all( [ baseOnly ? none : payload.find({ collection: "game-structures", where: { map: { equals: mapId } }, depth: 2, limit: 1000, overrideAccess: true, }), baseOnly ? none : payload.find({ collection: "resource-nodes", where: { map: { equals: mapId } }, depth: 1, limit: 5000, overrideAccess: true, }), payload.find({ collection: "map-roads", where: { map: { equals: mapId } }, depth: 0, limit: 5000, overrideAccess: true, }), payload.find({ collection: "map-zones", where: { map: { equals: mapId } }, depth: 1, limit: 5000, overrideAccess: true, }), baseOnly ? none : payload.find({ collection: "shipments", where: { and: [{ map: { equals: mapId } }, { status: { in: ["dispatched", "in_transit"] } }], }, depth: 2, limit: 200, sort: "-dispatchedAt", overrideAccess: true, }), listMapObjectives(payload, mapId, { includeRedacted }), ], ); const structures: StructureFeature[] = []; for (const doc of structuresRes.docs) { const structure = doc as unknown as GameStructure & { type: { id: number; name: string } }; const point = pointOf(structure.coordinates); if (!point) continue; const blueprint = typeof structure.type === "object" ? structure.type : null; const faction = structure.faction && typeof structure.faction === "object" ? structure.faction : null; const storageEntries = [ ...(structure.storedResources ?? []), ...((structure as GameStructure).voidStorage ?? []), ]; let storageUsedKg = 0; for (const entry of storageEntries) { const resource = typeof entry.resource === "object" ? entry.resource : null; storageUsedKg += (resource?.massPerUnit ?? 0) * entry.amount; } structures.push({ id: structure.id, name: structure.name, point, constructionStatus: structure.constructionStatus ?? "complete", constructionStartedAt: structure.constructionStartedAt ?? null, constructionCompletesAt: structure.constructionCompletesAt ?? null, constructionDurationMinutes: blueprint?.constructionDurationMinutes ?? null, storageUsedKg, storageCapacityKg: blueprint ? effectiveMaxMass(blueprint, structure.installedModules) : null, labelVisible: structure.labelVisible ?? null, labelPriority: structure.labelPriority ?? null, parentId: compoundParentId(structure), compoundChildren: 0, blueprintId: blueprint?.id ?? null, blueprintName: blueprint?.name ?? null, blueprintTerrain: (blueprint?.terrainType as "land" | "water" | undefined) ?? null, materials: (blueprint?.materials ?? []).map((material) => ({ resource: relationshipId(material.resource) ?? 0, resourceName: material.resource && typeof material.resource === "object" ? material.resource.name : "Resource", amount: material.amount ?? 0, })), resourcesInRange: (blueprint?.resourcesInRange ?? []).map((requirement) => ({ resource: relationshipId(requirement.resource), structure: null, range: requirement.range ?? null, })), structuresInRange: (blueprint?.structuresInRange ?? []).map((requirement) => ({ resource: null, structure: relationshipId(requirement.structure), range: requirement.range ?? null, })), factionName: faction && "name" in faction ? String(faction.name) : null, }); } // Compound pooling: children fold their storage into the hub feature and lose // their own map labels; the hub carries the compound label and ribbon totals. const featuresById = new Map(structures.map((feature) => [feature.id, feature])); const childrenByHub = new Map(); for (const feature of structures) { if (feature.parentId === null) continue; feature.labelVisible = false; const siblings = childrenByHub.get(feature.parentId) ?? []; siblings.push(feature); childrenByHub.set(feature.parentId, siblings); } for (const [hubId, children] of childrenByHub) { const hub = featuresById.get(hubId); if (!hub) continue; const totals = aggregateCompoundStorage(hub, children); hub.storageUsedKg = totals.storageUsedKg; hub.storageCapacityKg = totals.storageCapacityKg; hub.compoundChildren = children.length; } const relEntries = (value: unknown): { id: number; name: string }[] => (Array.isArray(value) ? value : []).map((entry) => typeof entry === "object" && entry !== null && "id" in entry ? { id: entry.id as number, name: String((entry as { name?: string }).name ?? "Resource") } : { id: entry as number, name: "Resource" }, ); const nodes = nodesRes.docs.map((node) => ({ id: node.id, name: node.name, point: pointOf(node.position) ?? [0, 0], description: node.description ?? null, resources: relEntries(node.resources), richness: node.richness ?? null, icon: node.icon ?? null, })); const roads = roadsRes.docs.map((road) => ({ id: road.id, name: road.name ?? null, description: road.description ?? null, surface: road.surface, speedMultiplier: road.speedMultiplier, strokeColor: road.strokeColor ?? null, strokeWeight: road.strokeWeight ?? null, strokeStyle: road.strokeStyle ?? null, labelVisible: road.labelVisible ?? null, points: isPointArray(road.points, 2) ? (road.points as MapPoint[]) : [], })); const zones = zonesRes.docs.map((zone) => ({ id: zone.id, name: zone.name ?? null, description: zone.description ?? null, type: zone.type, resources: relEntries(zone.resources), fillColor: zone.fillColor ?? null, strokeColor: zone.strokeColor ?? null, fillOpacity: zone.fillOpacity ?? null, strokeWeight: zone.strokeWeight ?? null, labelVisible: zone.labelVisible ?? null, points: isPointArray(zone.points, 3) ? (zone.points as MapPoint[]) : [], })); const shipments = shipmentsRes.docs.map((doc) => { const shipment = doc as unknown as Shipment & { origin: GameStructure; destination: GameStructure; transportVehicle: { name: string } | number | null; }; const vehicle = shipment.transportVehicle && typeof shipment.transportVehicle === "object" ? shipment.transportVehicle : null; const vehicleType = vehicle && typeof (vehicle as { type?: unknown }).type === "object" ? ((vehicle as { type: { name?: string } }).type.name ?? null) : null; return { id: shipment.id, name: shipment.name ?? null, status: shipment.status, routePath: isPointArray(shipment.routePath, 2) ? (shipment.routePath as MapPoint[]) : null, originName: shipment.origin?.name ?? null, originPoint: pointOf(shipment.origin?.coordinates), destinationName: shipment.destination?.name ?? null, destinationPoint: pointOf(shipment.destination?.coordinates), dispatchedAt: shipment.dispatchedAt ?? null, estimatedArrival: shipment.estimatedArrival ?? null, vehicleName: vehicleType, }; }); const response: MapFeaturesResponse = { map: { id: mapDoc.id, name: mapDoc.name, worldSizeWidth: worldW, worldSizeHeight: worldH, basemapMode: mapDoc.basemapMode, basemapImageUrl: mapDoc.basemapImage && typeof mapDoc.basemapImage === "object" ? (mapDoc.basemapImage.url ?? null) : null, tileUrlTemplate: mapDoc.tileUrlTemplate ?? null, minZoom: mapDoc.minZoom ?? 0, maxZoom: mapDoc.maxZoom ?? 12, defaultZoom: mapDoc.defaultZoom ?? 2, defaultCenter: [mapDoc.defaultCenterX ?? worldW / 2, mapDoc.defaultCenterY ?? worldH / 2], grid: gridConfigFromMapDoc(mapDoc as unknown as Record), }, structures, nodes, roads, zones, shipments, objectives, }; return NextResponse.json(response); }