import { describe, it, expect, beforeEach } from 'vitest';
import { db } from '@/lib/db/db';
import { campaignsRepo, charactersRepo, notesRepo } from '@/lib/db/repositories';
import { buildBackup, restoreBackup, clearAllData } from './backup';

beforeEach(async () => {
  await db.delete();
  await db.open();
});

describe('backup round-trip', () => {
  it('exports all data and restores it after a wipe', async () => {
    const c = await campaignsRepo.create({ name: 'Backed Up', system: '5e', description: '' });
    await charactersRepo.create(c.id, { system: '5e', name: 'Saved Hero', kind: 'pc', ancestry: '', className: '', level: 2 });
    await notesRepo.create(c.id, 'Saved Note');

    const backup = await buildBackup();
    await clearAllData();
    expect(await campaignsRepo.list()).toHaveLength(0);

    await restoreBackup(JSON.stringify(backup));
    const campaigns = await campaignsRepo.list();
    expect(campaigns).toHaveLength(1);
    expect(campaigns[0]!.name).toBe('Backed Up');
    expect(await charactersRepo.listByCampaign(c.id)).toHaveLength(1);
    expect(await notesRepo.listByCampaign(c.id)).toHaveLength(1);
  });

  it('rejects a non-backup file', async () => {
    await expect(restoreBackup('{"foo":1}')).rejects.toThrow();
    await expect(restoreBackup('not json')).rejects.toThrow();
  });
});
