"use server"; import config from "@payload-config"; import { isPayloadUser } from "@/utils/access-control/isPayloadUser"; import { getPayload } from "payload"; import type { User } from "@/payload-types"; import { emitGameEvent } from "@/utils/event-log/emit"; import { EventTypes } from "@/utils/event-log/eventTypes"; import { notifyUser } from "@/lib/notifications"; import type { DialogueCondition, DialogueFlagOp, FlowData, NpcDialogueEffect, } from "@/lib/npc-dialogue/dialogue"; interface ActionResult { success: boolean; error?: string; data?: T; } async function authenticate() { const payloadConfig = await config; const payload = await getPayload({ config: payloadConfig }); const { headers } = await import("next/headers"); const hdrs = await headers(); const { user } = await payload.auth({ headers: hdrs, canSetHeaders: false, }); if (!isPayloadUser(user)) { throw new Error("Unauthorized"); } return { payload, user }; } /** * Resolve the effect configured on a dialogue `event` node and run it. The * node is looked up server-side from the stored flowchart, so the client can * only trigger effects an admin has authored for this conversation. */ export async function triggerNpcDialogueEvent( npcId: number, nodeId: string, ): Promise { try { const { payload, user } = await authenticate(); const res = await payload.find({ collection: "npc-dialogues", where: { npc: { equals: npcId } }, limit: 1, depth: 0, overrideAccess: true, }); const flowData = res.docs[0]?.flowData as unknown as FlowData | undefined; if (!flowData || !Array.isArray(flowData.nodes)) { return { success: false, error: "This contact has no conversation configured." }; } const node = flowData.nodes.find((n) => n.id === nodeId); if (!node || node.type !== "event" || !node.data.effect) { // Nothing to trigger (or the node isn't an event): treated as a no-op. return { success: true }; } const effect: NpcDialogueEffect = node.data.effect; await runEffect(payload, user.id as number, npcId, effect); return { success: true }; } catch (error) { const message = error instanceof Error ? error.message : "Unknown error"; if (message === "Unauthorized") { return { success: false, error: "You must be logged in." }; } return { success: false, error: message }; } } async function runEffect( payload: Awaited>, userId: number, npcId: number, effect: NpcDialogueEffect, ): Promise { switch (effect.type) { case "notify": { await notifyUser(payload, { userId, type: "npc:dialogue", title: effect.title ?? "Conversation", message: effect.message, }); break; } case "emit": { await emitGameEvent(payload, { type: EventTypes.NpcDialogue, message: effect.message ?? "NPC dialogue event", actor: userId, targetCollection: "game-npcs", targetId: npcId, data: { effect: "emit" }, }); break; } case "reward": { // LLM/reward seam intentionally left unconfigured (see Phase 5). await emitGameEvent(payload, { type: EventTypes.NpcDialogue, message: effect.message ?? "NPC dialogue reward (unconfigured)", actor: userId, targetCollection: "game-npcs", targetId: npcId, data: { effect: "reward", unconfigured: true }, }); break; } case "flag": { const key = effect.flagKey?.trim(); if (!key) break; const op: DialogueFlagOp = effect.flagOp ?? "set_true"; const amount = effect.flagAmount ?? 0; await applyFlagEffect(payload, userId, key, op, amount); await emitGameEvent(payload, { type: EventTypes.NpcDialogue, message: `Conversation set flag "${key}" (${op}).`, actor: userId, targetCollection: "game-npcs", targetId: npcId, data: { effect: "flag", key, op, amount }, }); break; } } } /** * Effective value of a flag: player-specific entry takes priority; if absent, * fall back to the global entry (user is null). Missing flags read false / 0. */ async function readFlag( payload: Awaited>, userId: number, key: string, ): Promise<{ bool: boolean; num: number }> { // Player-specific flag (priority). const playerRes = await payload.find({ collection: "player-flags", where: { user: { equals: userId }, key: { equals: key }, }, limit: 1, depth: 0, overrideAccess: true, }); const playerDoc = playerRes.docs[0]; if (playerDoc) { if (playerDoc.flagType === "number") { const num = playerDoc.numberValue ?? 0; return { bool: num !== 0, num }; } const bool = playerDoc.boolValue === true; return { bool, num: bool ? 1 : 0 }; } // Global fallback (user is null). const globalRes = await payload.find({ collection: "player-flags", where: { user: { equals: null }, key: { equals: key }, }, limit: 1, depth: 0, overrideAccess: true, }); const globalDoc = globalRes.docs[0]; if (!globalDoc) return { bool: false, num: 0 }; if (globalDoc.flagType === "number") { const num = globalDoc.numberValue ?? 0; return { bool: num !== 0, num }; } const bool = globalDoc.boolValue === true; return { bool, num: bool ? 1 : 0 }; } /** Create-or-update a player flag according to the effect's write mode. */ async function applyFlagEffect( payload: Awaited>, userId: number, key: string, op: DialogueFlagOp, amount: number, ): Promise { const existing = await payload.find({ collection: "player-flags", where: { user: { equals: userId }, key: { equals: key }, }, limit: 1, depth: 0, overrideAccess: true, }); const doc = existing.docs[0]; if (op === "set_true" || op === "set_false") { const boolValue = op === "set_true"; if (doc) { await payload.update({ collection: "player-flags", id: doc.id, data: { flagType: "boolean", boolValue }, overrideAccess: true, }); } else { await payload.create({ collection: "player-flags", data: { user: userId, key, flagType: "boolean", boolValue }, overrideAccess: true, }); } return; } if (op === "set_number") { if (doc) { await payload.update({ collection: "player-flags", id: doc.id, data: { flagType: "number", numberValue: amount }, overrideAccess: true, }); } else { await payload.create({ collection: "player-flags", data: { user: userId, key, flagType: "number", numberValue: amount }, overrideAccess: true, }); } return; } // add: numeric flags accumulate; boolean flags convert (true = 1). const current = doc ? doc.flagType === "number" ? doc.numberValue ?? 0 : doc.boolValue ? 1 : 0 : 0; const numberValue = current + amount; if (doc) { await payload.update({ collection: "player-flags", id: doc.id, data: { flagType: "number", numberValue }, overrideAccess: true, }); } else { await payload.create({ collection: "player-flags", data: { user: userId, key, flagType: "number", numberValue }, overrideAccess: true, }); } } /** * Evaluate a dialogue `condition` node against the reading user's live * web-app state (player flags). The node is looked up server-side from the * stored flowchart, so the client can only evaluate conditions an admin * authored for this conversation. */ export async function evaluateNpcDialogueCondition( npcId: number, nodeId: string, ): Promise> { try { const { payload, user } = await authenticate(); const res = await payload.find({ collection: "npc-dialogues", where: { npc: { equals: npcId } }, limit: 1, depth: 0, overrideAccess: true, }); const flowData = res.docs[0]?.flowData as unknown as FlowData | undefined; const node = flowData?.nodes?.find((n) => n.id === nodeId); if (!node || node.type !== "condition" || !node.data.condition) { // Not a condition node: nothing to branch on. return { success: true, data: false }; } const value = await evaluateCondition(payload, user.id as number, node.data.condition); return { success: true, data: value }; } catch (error) { const message = error instanceof Error ? error.message : "Unknown error"; if (message === "Unauthorized") { return { success: false, error: "You must be logged in." }; } return { success: false, error: message }; } } /** * Evaluate every choice's visibility gate for a `choice` node in one round * trip. Ungated choices are always visible; gated ones appear only while the * reading user's flags satisfy their condition. The node is looked up * server-side from the stored flowchart, so clients never see gate config * for conversations an admin has not authored. */ export async function evaluateNpcDialogueChoices( npcId: number, nodeId: string, ): Promise> { try { const { payload, user } = await authenticate(); const res = await payload.find({ collection: "npc-dialogues", where: { npc: { equals: npcId } }, limit: 1, depth: 0, overrideAccess: true, }); const flowData = res.docs[0]?.flowData as unknown as FlowData | undefined; const node = flowData?.nodes?.find((n) => n.id === nodeId); if (!node || node.type !== "choice") { // Not a choice node: nothing to gate. return { success: true, data: [] }; } const visible: boolean[] = []; for (const choice of node.data.choices ?? []) { if (!choice.condition?.key?.trim()) { visible.push(true); continue; } visible.push(await evaluateCondition(payload, user.id as number, choice.condition)); } return { success: true, data: visible }; } catch (error) { const message = error instanceof Error ? error.message : "Unknown error"; if (message === "Unauthorized") { return { success: false, error: "You must be logged in." }; } return { success: false, error: message }; } } async function evaluateCondition( payload: Awaited>, userId: number, condition: DialogueCondition, ): Promise { const flag = await readFlag(payload, userId, condition.key); const amount = condition.amount ?? 0; switch (condition.op) { case "is_true": return flag.bool; case "is_false": return !flag.bool; case "gte": return flag.num >= amount; case "lte": return flag.num <= amount; case "gt": return flag.num > amount; case "lt": return flag.num < amount; case "eq": return flag.num === amount; } }