import { describe, it, expect, afterEach } from 'vitest';
import { mkdtempSync, readFileSync, rmSync, writeFileSync, existsSync } from 'fs';
import { join } from 'path';
import { tmpdir } from 'os';
import { persistConfig } from './persistence.js';
import { configSchema } from './schema.js';

const testRoots: string[] = [];

afterEach(() => {
  while (testRoots.length > 0) {
    const dir = testRoots.pop();
    if (!dir) {continue;}
    try {
      rmSync(dir, { recursive: true, force: true });
    } catch {}
  }
});

function makeConfig() {
  return configSchema.parse({
    telegram: { bot_token: 'test-token', allowed_chat_ids: [1] },
    models: { default: { provider: 'anthropic', model: 'claude-3' } },
    hooks: { confirm: ['shell.exec'], log: [], silent: [] },
  });
}

describe('persistConfig', () => {
  it('writes config to target path', () => {
    const dir = mkdtempSync(join(tmpdir(), 'flynn-config-persist-'));
    testRoots.push(dir);
    const configPath = join(dir, 'config.yaml');

    persistConfig(configPath, makeConfig());
    const written = readFileSync(configPath, 'utf-8');
    expect(written).toContain('telegram:');
    expect(written).toContain('models:');
  });

  it('creates .bak when overwriting existing config', () => {
    const dir = mkdtempSync(join(tmpdir(), 'flynn-config-persist-'));
    testRoots.push(dir);
    const configPath = join(dir, 'config.yaml');

    writeFileSync(configPath, 'legacy: true\n', 'utf-8');
    persistConfig(configPath, makeConfig());

    const backupPath = `${configPath}.bak`;
    expect(existsSync(backupPath)).toBe(true);
    expect(readFileSync(backupPath, 'utf-8')).toContain('legacy: true');
  });
});
