import { describe, it, expect, beforeEach } from 'vitest';
import { promises as fs } from 'node:fs';
import path from 'node:path';
import os from 'node:os';
import { CloudStore } from './campaigns';

describe('CloudStore', () => {
  let dir: string;
  let store: CloudStore;
  beforeEach(async () => { dir = await fs.mkdtemp(path.join(os.tmpdir(), 'cloud-')); store = new CloudStore(dir); });

  it('creates a campaign and lets a player join by invite', async () => {
    const c = await store.createCampaign('gm1', 'Strahd', '5e');
    expect(c.ownerUserId).toBe('gm1');
    expect(c.inviteCode).toHaveLength(6);
    expect(store.isMember(c.id, 'gm1')).toBe(true);

    expect(await store.joinByInvite('p1', 'ZZZZZZ')).toBeNull(); // bad code
    const joined = await store.joinByInvite('p1', c.inviteCode);
    expect(joined?.id).toBe(c.id);
    expect(store.isMember(c.id, 'p1')).toBe(true);
    expect(store.isMember(c.id, 'stranger')).toBe(false);

    const forP1 = await store.listForUser('p1');
    expect(forP1[0]).toMatchObject({ id: c.id, role: 'member' });
    expect((await store.listForUser('gm1'))[0]).toMatchObject({ role: 'owner' });
  });

  it('enforces character ownership on upsert', async () => {
    const c = await store.createCampaign('gm1', 'C', '5e');
    await store.joinByInvite('p1', c.inviteCode);
    await store.joinByInvite('p2', c.inviteCode);

    expect(await store.putCharacter('stranger', c.id, { id: 'ch1', name: 'X', data: '{}' })).toBeNull(); // not a member
    const r = await store.putCharacter('p1', c.id, { id: 'ch1', name: 'Lia', data: '{"hp":1}' });
    expect(r?.ownerUserId).toBe('p1');
    expect(await store.putCharacter('p2', c.id, { id: 'ch1', name: 'hijack', data: '{}' })).toBeNull(); // p2 can't update p1's char

    const all = await store.listCharacters(c.id);
    expect(all).toHaveLength(1);
    expect(all[0]!.name).toBe('Lia');
    expect(await store.usageBytes('p1')).toBeGreaterThan(0);
  });

  it('lets the char owner or campaign owner delete; persists across instances', async () => {
    const c = await store.createCampaign('gm1', 'C', '5e');
    await store.joinByInvite('p1', c.inviteCode);
    await store.putCharacter('p1', c.id, { id: 'ch1', name: 'Lia', data: '{}' });

    expect(await store.removeCharacter('p2', 'ch1')).toBe(false); // unrelated user
    expect(await store.removeCharacter('gm1', 'ch1')).toBe(true); // campaign owner may remove

    const store2 = new CloudStore(dir);
    await store2.load();
    expect((await store2.listForUser('gm1'))[0]?.id).toBe(c.id);
    expect(await store2.listCharacters(c.id)).toHaveLength(0);
  });
});
