import { describe, expect, it, beforeEach, afterEach } from 'vitest';
import { mkdtempSync, readFileSync, writeFileSync, rmSync, existsSync } from 'node:fs';
import { tmpdir } from 'node:os';
import { join } from 'node:path';
import { preTrustProject } from '../src/core/claude-trust.js';

describe('preTrustProject', () => {
  let dir: string;
  let cfg: string;
  beforeEach(() => {
    dir = mkdtempSync(join(tmpdir(), 'arb-trust-'));
    cfg = join(dir, '.claude.json');
  });
  afterEach(() => {
    rmSync(dir, { recursive: true, force: true });
  });

  it('crée le fichier s’il est absent et marque le worktree approuvé', () => {
    expect(preTrustProject('/home/u/proj-wt-x', cfg)).toBe(true);
    const data = JSON.parse(readFileSync(cfg, 'utf8'));
    expect(data.projects['/home/u/proj-wt-x'].hasTrustDialogAccepted).toBe(true);
  });

  it('préserve la config existante (autres clés et projets)', () => {
    writeFileSync(cfg, JSON.stringify({ theme: 'dark', projects: { '/other': { foo: 1 } } }));
    expect(preTrustProject('/home/u/new', cfg)).toBe(true);
    const data = JSON.parse(readFileSync(cfg, 'utf8'));
    expect(data.theme).toBe('dark');
    expect(data.projects['/other']).toEqual({ foo: 1 });
    expect(data.projects['/home/u/new'].hasTrustDialogAccepted).toBe(true);
  });

  it('fichier corrompu → abandon SANS écraser (retourne false)', () => {
    writeFileSync(cfg, '{ this is not json');
    expect(preTrustProject('/home/u/x', cfg)).toBe(false);
    expect(readFileSync(cfg, 'utf8')).toBe('{ this is not json'); // intact
    expect(existsSync(`${cfg}.arb-tmp`)).toBe(false);
  });
});
