import test from "node:test"; import assert from "node:assert/strict"; import { mkdtempSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { StateDatabase } from "../src/persistence/stateDb.js"; import { FriendService } from "../src/friends/service.js"; function setup () { const dir = mkdtempSync(join(tmpdir(), "mmo-friends-")); const stateDb = new StateDatabase(join(dir, "state.sqlite")); const accountA = stateDb.createAccount("admin-1", true); const accountB = stateDb.createAccount("admin-2", true); const left = stateDb.createCharacter(accountA.account_id, "Ada", "West", "female", 8, 8); const right = stateDb.createCharacter(accountB.account_id, "Ben", "East", "male", 8, 8); return { stateDb, friends: new FriendService(stateDb), leftId: left.character_id, rightId: right.character_id }; } test("a friend request must be accepted before both sides are friends", () => { const { stateDb, friends, leftId, rightId } = setup(); try { const pending = friends.request(leftId, rightId); assert.equal(pending.outgoing.length, 1); assert.equal(pending.friends.length, 0); assert.equal(friends.snapshot(rightId).incoming[0].firstName, "Ada"); friends.accept(rightId, leftId); assert.equal(friends.snapshot(leftId).friends.length, 1); assert.equal(friends.snapshot(rightId).friends[0].lastName, "West"); assert.equal(friends.snapshot(leftId).outgoing.length, 0); assert.equal(friends.snapshot(rightId).incoming.length, 0); } finally { stateDb.close(); } }); test("removing a friend removes them for both characters", () => { const { stateDb, friends, leftId, rightId } = setup(); try { friends.request(leftId, rightId); friends.accept(rightId, leftId); friends.remove(leftId, rightId); assert.equal(friends.snapshot(leftId).friends.length, 0); assert.equal(friends.snapshot(rightId).friends.length, 0); } finally { stateDb.close(); } }); test("a reverse request accepts the pending invite", () => { const { stateDb, friends, leftId, rightId } = setup(); try { friends.request(leftId, rightId); friends.request(rightId, leftId); assert.equal(friends.snapshot(leftId).friends.length, 1); assert.equal(friends.snapshot(rightId).incoming.length, 0); } finally { stateDb.close(); } }); test("friends list is the pigeon address book of first and last names", () => { const { stateDb, friends, leftId, rightId } = setup(); try { friends.request(leftId, rightId); friends.accept(rightId, leftId); const found = friends.findByFullName("Ben", "East"); assert.equal(found.characterId, rightId); assert.deepEqual(friends.listFriends(leftId)[0], found); } finally { stateDb.close(); } });