import { describe, it, expect } from 'vitest';
import { RoomHub, type Sender } from './rooms';
import type { ServerMessage, Snapshot } from '@/lib/sync/messages';
import { characterSchema, type Character } from '@/lib/schemas';

function fake(): Sender & { msgs: ServerMessage[] } {
  const msgs: ServerMessage[] = [];
  return { msgs, send: (m) => msgs.push(m) };
}
const snap: Snapshot = { campaignName: 'C', calendarDay: null, party: [], encounter: null, map: null, mapImageId: null, quests: [] };
const char: Character = characterSchema.parse({
  id: 'ch1', campaignId: 'cmp1', system: '5e', name: 'Lia',
  abilities: { str: 10, dex: 12, con: 14, int: 10, wis: 13, cha: 8 },
  hp: { current: 18, max: 24, temp: 0 }, createdAt: 't', updatedAt: 't',
});
function lastOf<T extends ServerMessage['t']>(s: ReturnType<typeof fake>, t: T): Extract<ServerMessage, { t: T }> | undefined {
  return [...s.msgs].reverse().find((m): m is Extract<ServerMessage, { t: T }> => m.t === t);
}
function hostAndJoin(hub: RoomHub) {
  const gm = fake(); hub.host(gm);
  const hosted = lastOf(gm, 'hosted') as Extract<ServerMessage, { t: 'hosted' }>;
  const player = fake(); hub.join(player, hosted.joinCode);
  return { gm, player, secret: hosted.gmSecret };
}

describe('RoomHub', () => {
  it('hosts a room and lets a player join + receive snapshots; GM is authoritative', () => {
    const hub = new RoomHub();
    const gm = fake();
    hub.host(gm);
    const hosted = lastOf(gm, 'hosted')!;
    expect(hosted).toBeTruthy();
    const code = (hosted as Extract<ServerMessage, { t: 'hosted' }>).joinCode;
    const secret = (hosted as Extract<ServerMessage, { t: 'hosted' }>).gmSecret;

    const player = fake();
    hub.join(player, code);
    expect(lastOf(player, 'joined')).toBeTruthy();

    hub.state(gm, secret, snap);
    expect(lastOf(player, 'snapshot')).toMatchObject({ snapshot: { campaignName: 'C' } });
  });

  it('rejects state from a non-GM and from a wrong secret', () => {
    const hub = new RoomHub();
    const gm = fake(); hub.host(gm);
    const player = fake();
    const code = (lastOf(gm, 'hosted') as Extract<ServerMessage, { t: 'hosted' }>).joinCode;
    hub.join(player, code);

    hub.state(player, 'whatever', snap);
    expect(lastOf(player, 'error')?.code).toBe('forbidden');
    hub.state(gm, 'wrong-secret', snap);
    expect(lastOf(gm, 'error')?.code).toBe('forbidden');
  });

  it('enforces an optional join password', () => {
    const hub = new RoomHub();
    const gm = fake(); hub.host(gm, 'sesame');
    const code = (lastOf(gm, 'hosted') as Extract<ServerMessage, { t: 'hosted' }>).joinCode;
    const p1 = fake(); hub.join(p1, code, 'nope');
    expect(lastOf(p1, 'error')?.code).toBe('bad-password');
    const p2 = fake(); hub.join(p2, code, 'sesame');
    expect(lastOf(p2, 'joined')).toBeTruthy();
  });

  it('reports no-room for a bad code, and resumes a room by GM secret', () => {
    const hub = new RoomHub();
    const stray = fake(); hub.join(stray, 'ZZZZZZ');
    expect(lastOf(stray, 'error')?.code).toBe('no-room');

    const gm = fake(); hub.host(gm);
    const hosted = lastOf(gm, 'hosted') as Extract<ServerMessage, { t: 'hosted' }>;
    const gm2 = fake(); hub.host(gm2, undefined, hosted.gmSecret);
    const resumed = lastOf(gm2, 'hosted') as Extract<ServerMessage, { t: 'hosted' }>;
    expect(resumed.roomId).toBe(hosted.roomId);
    expect(hub.roomCount()).toBe(1);
  });

  it('caches + serves images and evicts idle rooms on sweep', () => {
    let t = 0;
    const hub = new RoomHub(() => t);
    const gm = fake(); hub.host(gm);
    const hosted = lastOf(gm, 'hosted') as Extract<ServerMessage, { t: 'hosted' }>;
    hub.image(gm, hosted.gmSecret, 'map1', 'data:abc');
    const player = fake(); hub.join(player, hosted.joinCode);
    hub.requestImage(player, 'map1');
    expect(lastOf(player, 'mapImage')).toMatchObject({ id: 'map1', dataUrl: 'data:abc' });

    t += 7 * 60 * 60 * 1000; // past TTL
    hub.sweep();
    expect(hub.roomCount()).toBe(0);
  });

  it('routes a seat claim → GM grant → player gets their sheet', () => {
    const hub = new RoomHub();
    const { gm, player, secret } = hostAndJoin(hub);

    hub.claimSeat(player, 'ch1', char);
    const req = lastOf(gm, 'seatRequest')!;
    expect(req).toMatchObject({ characterId: 'ch1' });
    expect(req.offlineSnapshot?.name).toBe('Lia');

    hub.seatGrant(gm, secret, req.playerId, char);
    expect(lastOf(player, 'seatGranted')).toMatchObject({ character: { id: 'ch1' } });
  });

  it('forwards a seated player patch/roll, and drops them from non-seated sockets', () => {
    const hub = new RoomHub();
    const { gm, player, secret } = hostAndJoin(hub);

    // Not seated yet → patch is dropped.
    hub.playerPatch(player, 'ch1', { hp: { current: 1, max: 24, temp: 0 } });
    expect(lastOf(gm, 'playerPatched')).toBeUndefined();

    hub.claimSeat(player, 'ch1');
    hub.seatGrant(gm, secret, lastOf(gm, 'seatRequest')!.playerId, char);

    hub.playerPatch(player, 'ch1', { hp: { current: 7, max: 24, temp: 0 } });
    expect(lastOf(gm, 'playerPatched')).toMatchObject({ characterId: 'ch1', diff: { hp: { current: 7 } } });

    hub.playerRoll(player, 'ch1', 'Sword', '1d20+5', 18, '[13]+5');
    expect(lastOf(gm, 'rollBroadcast')).toMatchObject({ playerName: 'Lia', total: 18 });

    // A patch for a character the player doesn't hold is rejected.
    const before = gm.msgs.filter((m) => m.t === 'playerPatched').length;
    hub.playerPatch(player, 'someone-else', { hp: { current: 0, max: 24, temp: 0 } });
    expect(gm.msgs.filter((m) => m.t === 'playerPatched').length).toBe(before);
  });

  it('broadcasts a roster (GM + players) to everyone', () => {
    const hub = new RoomHub();
    const { gm, player } = hostAndJoin(hub);
    const roster = lastOf(gm, 'roster');
    expect(roster?.players.map((p) => p.name)).toContain('GM');
    expect(roster?.players).toHaveLength(2); // GM + 1 player
    expect(lastOf(player, 'roster')?.players).toHaveLength(2); // players see the roster too
  });

  it('routes a private handout to the target player ONLY', () => {
    const hub = new RoomHub();
    const gm = fake(); hub.host(gm);
    const hosted = lastOf(gm, 'hosted') as Extract<ServerMessage, { t: 'hosted' }>;
    const p1 = fake(); hub.join(p1, hosted.joinCode);
    const p2 = fake(); hub.join(p2, hosted.joinCode);
    const roster = lastOf(gm, 'roster')!;
    const targetId = roster.players.find((p) => p.playerId !== 'gm')!.playerId; // first player (insertion order)

    hub.privateState(gm, hosted.gmSecret, targetId, { title: 'Secret', body: 'just for you' });
    expect(lastOf(p1, 'privateHandout')).toMatchObject({ handout: { title: 'Secret' } });
    expect(lastOf(p2, 'privateHandout')).toBeUndefined(); // a non-recipient never receives it
  });

  it('rejects privateState from a non-GM', () => {
    const hub = new RoomHub();
    const { player } = hostAndJoin(hub);
    hub.privateState(player, 'not-the-secret', 'gm', { title: 'x', body: 'y' });
    expect(lastOf(player, 'error')?.code).toBe('forbidden');
  });

  it('lets a player set a display name shown in the roster', () => {
    const hub = new RoomHub();
    const { gm, player } = hostAndJoin(hub);
    hub.setName(player, 'Alice');
    expect(lastOf(gm, 'roster')!.players.find((p) => p.name === 'Alice')).toBeTruthy();
  });

  it('routes chat: table to all, whisper to the target only', () => {
    const hub = new RoomHub();
    const gm = fake(); hub.host(gm);
    const hosted = lastOf(gm, 'hosted') as Extract<ServerMessage, { t: 'hosted' }>;
    const p1 = fake(); hub.join(p1, hosted.joinCode);
    const p2 = fake(); hub.join(p2, hosted.joinCode);
    const p1id = lastOf(gm, 'roster')!.players.filter((p) => p.playerId !== 'gm')[0]!.playerId;
    const chatCount = (s: ReturnType<typeof fake>) => s.msgs.filter((m) => m.t === 'chat').length;

    // GM table → both players
    hub.chat(gm, 'hello table');
    expect(lastOf(p1, 'chat')).toMatchObject({ from: 'GM', body: 'hello table', scope: 'table' });
    expect(lastOf(p2, 'chat')).toMatchObject({ scope: 'table' });

    // GM whisper to p1 → only p1
    const p2c = chatCount(p2);
    hub.chat(gm, 'psst', p1id);
    expect(lastOf(p1, 'chat')).toMatchObject({ from: 'GM', body: 'psst', scope: 'whisper' });
    expect(chatCount(p2)).toBe(p2c);

    // Player table → GM + the other player (not the sender)
    hub.chat(p1, 'hi all');
    expect(lastOf(gm, 'chat')).toMatchObject({ body: 'hi all', scope: 'table' });
    expect(lastOf(p2, 'chat')).toMatchObject({ body: 'hi all', scope: 'table' });

    // Player whisper → GM only
    const p2c2 = chatCount(p2);
    hub.chat(p1, 'private q', 'gm');
    expect(lastOf(gm, 'chat')).toMatchObject({ body: 'private q', scope: 'whisper' });
    expect(chatCount(p2)).toBe(p2c2);
  });
});
